auth

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package auth implements the Authorization Service client for managing share records (create, revoke, extend, list) and the authorization callout handler.

Index

Constants

View Source
const (
	ErrCodeNotFound       = "SHARE_NOT_FOUND"
	ErrCodeAlreadyRevoked = "SHARE_ALREADY_REVOKED"
	ErrCodeExpired        = "SHARE_EXPIRED"
	ErrCodeInvalidInput   = "INVALID_INPUT"
	ErrCodeInternal       = "INTERNAL_ERROR"
)

Admin API error codes for state-conflict guards.

View Source
const (
	DefaultCacheTTLCeiling = time.Hour
	DefaultCacheDenyTTL    = 60 * time.Second
)

Default cache TTLs applied when a caller does not supply its own.

View Source
const GSI1IndexName = "GSI1"

GSI1IndexName is the name of the DynamoDB GSI used for authorization lookups by targetVpcArn.

View Source
const (
	GSI2IndexName = "GSI2"
)

GSI2IndexName GSI index names.

View Source
const SourceVpcArnHeader = "Htsget-Context-SourceVpcArn"

SourceVpcArnHeader is the request header carrying the requester's source VPC ARN on an htsget-rs authorization callout.

htsget-rs forwards configured context values as headers named with its `Htsget-Context-` prefix, so a `forward.context.extensions` entry of `{ json_path = "$.requestContext.identity.sourceVpcArn", name = "SourceVpcArn" }` arrives as this header. htsget-rs issues the callout as a bare GET with headers only, so this is the only channel the identity travels over.

View Source
const VaryIdentityHeaders = SourceVpcArnHeader

VaryIdentityHeaders is the Vary header value the authorization service emits on every callout response. It names the forwarded identity header(s) that the authorization decision depends on, so that:

  • any cache implementing secondary cache keys can revalidate correctly, and
  • the fail-closed storage precondition is satisfiable.

Per-requester isolation itself rests on the declared cache key in htsget-rs, NOT on this header.

Variables

View Source
var ErrShareAlreadyRevoked = fmt.Errorf("share is already revoked")

ErrShareAlreadyRevoked indicates the share has already been revoked.

View Source
var ErrShareExpired = fmt.Errorf("share has already expired")

ErrShareExpired indicates the share has already expired.

View Source
var ErrShareNotFound = fmt.Errorf("share not found")

ErrShareNotFound indicates the requested share ID does not exist.

Functions

func ComputeCacheControl

func ComputeCacheControl(records []*model.ShareRecord, now time.Time, ceiling time.Duration, denyTTL time.Duration) string

ComputeCacheControl computes the Cache-Control header value for an authorization response.

For allow responses (active shares exist):

  • Computes remaining lifetime for each share:
  • Unlimited shares (ExpiresAt == nil): use ceiling as their contribution
  • Expiring shares: remaining = ExpiresAt - now
  • Takes min(all remaining lifetimes), then caps at ceiling
  • Returns "s-maxage=<seconds>, public" so a shared cache is permitted to store and reuse the response even when the callout request carries an Authorization header (RFC 9111 §3.5).

For deny responses (no active shares):

  • Returns "max-age=<denyTTL seconds>" for short negative caching. This uses plain max-age rather than s-maxage so the deny response is also usable by a private cache, and because the deny path carries no credentials concern.

Where no safe lifetime can be determined (should not happen with the above logic, but as a fallback):

  • Returns "no-store".

Types

type AdminHandler

type AdminHandler struct {
	// contains filtered or unexported fields
}

AdminHandler provides HTTP-style handlers for the admin API endpoints (create, revoke, extend, list) of the Authorization Service. These handlers are designed to be deployed as a Lambda behind API Gateway.

func NewAdminHandler

func NewAdminHandler(store *ShareStore) *AdminHandler

NewAdminHandler creates a new AdminHandler backed by the given ShareStore.

func (*AdminHandler) HandleCreate

func (h *AdminHandler) HandleCreate(ctx context.Context, req CreateRequest) (*CreateResponse, *ErrorResponse, int)

HandleCreate processes a create share request. It persists a ShareRecord to DynamoDB and returns the share ID. Uses idempotent creation to prevent duplicates.

func (*AdminHandler) HandleExtend

func (h *AdminHandler) HandleExtend(ctx context.Context, req ExtendRequest) (*ExtendResponse, *ErrorResponse, int)

HandleExtend processes an extend share request. It performs a conditional update to expiresAt, with state-conflict guards for revoked and expired shares.

func (*AdminHandler) HandleList

func (h *AdminHandler) HandleList(ctx context.Context, req ListRequest) (*ListResponse, *ErrorResponse, int)

HandleList processes a list shares request. It queries GSI2 by researcherAccountId (if provided) or scans all records.

func (*AdminHandler) HandleRequest

func (h *AdminHandler) HandleRequest(ctx context.Context, method, path string, body []byte) (int, []byte, error)

HandleRequest routes an incoming API Gateway request to the appropriate handler based on the HTTP method and path. This serves as the Lambda handler entry point.

func (*AdminHandler) HandleRevoke

func (h *AdminHandler) HandleRevoke(ctx context.Context, req RevokeRequest) (*RevokeResponse, *ErrorResponse, int)

HandleRevoke processes a revoke share request. It performs a conditional update setting revokedAt, with state-conflict guards for already-revoked and expired shares.

type CalloutHandler

type CalloutHandler struct {
	// contains filtered or unexported fields
}

CalloutHandler handles authorization callouts from htsget-rs. It queries DynamoDB for active shares matching the source VPC ARN and returns the authorization response.

func NewCalloutHandler

func NewCalloutHandler(client internalaws.DynamoDBClient, tableName string) *CalloutHandler

NewCalloutHandler creates a new CalloutHandler with the given DynamoDB client and table name.

func (*CalloutHandler) HandleCallout

func (h *CalloutHandler) HandleCallout(ctx context.Context, sourceVpcArn string) (*CalloutResponse, error)

HandleCallout processes an authorization callout for the given source VPC ARN and returns only the response body, using the default cache TTLs.

This is a convenience wrapper over HandleCalloutWithHeaders for callers that do not care about the cache headers; the deployed Lambda uses the full form so it can emit them. Behaviour is otherwise identical: active shares contribute location entries, no match yields an empty htsgetAuth array (deny), and an unreachable store yields a deny plus an error.

func (*CalloutHandler) HandleCalloutWithHeaders

func (h *CalloutHandler) HandleCalloutWithHeaders(ctx context.Context, sourceVpcArn string, ceiling time.Duration, denyTTL time.Duration) (*CalloutResult, error)

HandleCalloutWithHeaders processes an authorization callout for the given source VPC ARN and computes the Cache-Control header value based on the matched shares' remaining lifetimes.

Parameters:

  • ctx: context for the DynamoDB query
  • sourceVpcArn: the requester's VPC ARN
  • ceiling: the maximum allowed max-age (TTL ceiling)
  • denyTTL: the max-age for deny responses

Returns a CalloutResult containing both the response and the Cache-Control header.

type CalloutResponse

type CalloutResponse struct {
	// Version is the schema version (always 1).
	Version int `json:"version"`

	// HtsgetAuth is the array of location entries with S3 prefixes.
	// An empty array means deny (no access).
	HtsgetAuth []LocationEntry `json:"htsgetAuth"`
}

CalloutResponse represents the htsget-rs authorization callout response. It conforms to the htsget-rs authorization response schema (version 1).

type CalloutResult

type CalloutResult struct {
	// Response is the htsget-rs authorization callout response.
	Response *CalloutResponse

	// CacheControl is the Cache-Control header value to include in the HTTP response.
	CacheControl string

	// Vary is the Vary header value naming every forwarded identity header
	// the decision depends on, so that any cache implementing secondary cache
	// keys can revalidate correctly.
	Vary string
}

CalloutResult contains the authorization callout response and the Cache-Control header value.

type CreateInput

type CreateInput struct {
	ResearcherAccountID string
	TargetVpcArn        string
	LibraryIDs          []string
	S3Prefixes          []string
	// Files records the individual resolved files for manifest generation. Optional,
	// it never affects authorization, which is granted by S3Prefixes.
	Files     []model.ShareFile
	ExpiresAt *time.Time
}

CreateInput contains the parameters for creating a new ShareRecord.

type CreateRequest

type CreateRequest struct {
	ResearcherAccountID string   `json:"researcherAccountId"`
	TargetVpcArn        string   `json:"targetVpcArn"`
	LibraryIDs          []string `json:"libraryIds"`
	S3Prefixes          []string `json:"s3Prefixes"`
	ExpiresAt           *string  `json:"expiresAt,omitempty"` // ISO 8601 or null for unlimited
}

CreateRequest represents the JSON body for the create share endpoint.

type CreateResponse

type CreateResponse struct {
	ShareID             string   `json:"shareId"`
	ResearcherAccountID string   `json:"researcherAccountId"`
	LibraryIDs          []string `json:"libraryIds"`
	S3Prefixes          []string `json:"s3Prefixes"`
	CreatedAt           string   `json:"createdAt"`
	ExpiresAt           *string  `json:"expiresAt,omitempty"`
	Reused              bool     `json:"reused"`
}

CreateResponse represents the JSON response for the create share endpoint.

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Code    string `json:"code"`
	Details string `json:"details,omitempty"`
}

ErrorResponse represents a JSON error response.

type ExtendRequest

type ExtendRequest struct {
	ShareID  string `json:"shareId"`
	Duration string `json:"duration"` // Go duration string, e.g. "168h"
}

ExtendRequest represents the JSON body for the extend share endpoint.

type ExtendResponse

type ExtendResponse struct {
	ShareID   string `json:"shareId"`
	ExpiresAt string `json:"expiresAt"`
}

ExtendResponse represents the JSON response for the extend share endpoint.

type ListRequest

type ListRequest struct {
	ResearcherAccountID string `json:"researcherAccountId,omitempty"` // optional filter
}

ListRequest represents the query parameters for the list shares endpoint.

type ListResponse

type ListResponse struct {
	Shares []ShareRecordResponse `json:"shares"`
}

ListResponse represents the JSON response for the list shares endpoint.

type LocationEntry

type LocationEntry struct {
	// Location contains the S3 key prefix that the htsget id must start with.
	Location LocationID `json:"location"`

	// Rules is an optional array of AccessRules. Omitted means unrestricted access.
	Rules []model.AccessRule `json:"rules,omitempty"`
}

LocationEntry represents a single location in the htsgetAuth response.

This maps onto htsget-rs's `AuthorizationRule`, which accepts exactly two fields: `location` and an optional `rules`.

type LocationID

type LocationID struct {
	// Prefix is the bucket-less S3 key prefix for the location, e.g.
	// "demo/L2400001/". It is matched with `starts_with` against the htsget id.
	Prefix string `json:"prefix"`
}

LocationID contains the prefix matcher for a location entry.

It deserialises in htsget-rs as a `LocationWrapper::String` carrying only a `PrefixOrId::Prefix`. Two deliberate choices:

  • `prefix`, not `id`. htsget-rs matches `id` by equality against the request path (e.g. "demo/L2400001/NA12878"), whereas a share grants access to a directory (e.g. "demo/L2400001/"). Only `prefix` has the right semantics.

  • No backend. Omitting it leaves htsget-rs with a defaulted backend, which `into_remote_locations()` filters out, so htsget-rs resolves the object against its own statically configured location instead. The share decides *what* may be read; the htsget-rs deployment decides *where from*. Emitting a backend here would require this service to know the storage topology and would force htsget-rs to hold broad S3 read permissions.

type RevokeRequest

type RevokeRequest struct {
	ShareID string `json:"shareId"`
}

RevokeRequest represents the JSON body for the revoke share endpoint.

type RevokeResponse

type RevokeResponse struct {
	ShareID   string `json:"shareId"`
	RevokedAt string `json:"revokedAt"`
}

RevokeResponse represents the JSON response for the revoke share endpoint.

type ShareRecordResponse

type ShareRecordResponse struct {
	ShareID             string   `json:"shareId"`
	ResearcherAccountID string   `json:"researcherAccountId"`
	TargetVpcArn        string   `json:"targetVpcArn"`
	LibraryIDs          []string `json:"libraryIds"`
	S3Prefixes          []string `json:"s3Prefixes"`
	CreatedAt           string   `json:"createdAt"`
	ExpiresAt           *string  `json:"expiresAt,omitempty"`
	RevokedAt           *string  `json:"revokedAt,omitempty"`
	Status              string   `json:"status"`
}

ShareRecordResponse represents a single share record in the list response.

type ShareStore

type ShareStore struct {
	// contains filtered or unexported fields
}

ShareStore provides CRUD operations for ShareRecords backed by DynamoDB.

func NewShareStore

func NewShareStore(client internalaws.DynamoDBClient, tableName string) *ShareStore

NewShareStore creates a new ShareStore with the given DynamoDB client and table name.

func (*ShareStore) Create

func (s *ShareStore) Create(ctx context.Context, input CreateInput) (*model.ShareRecord, error)

Create persists a new ShareRecord with a generated ULID, computed expiry, s3Prefixes, and status=active. Returns the created ShareRecord.

The target VPC ARN is validated here rather than only at the CLI, because this is the single write path every caller shares — the share command, the canary, and the admin Lambda's create endpoint. A malformed ARN produces no error downstream: it is stored happily and then never matches an authorization callout, so the failure surfaces much later as an unexplained deny.

func (*ShareStore) CreateIdempotent

func (s *ShareStore) CreateIdempotent(ctx context.Context, input CreateInput) (*model.ShareRecord, bool, error)

CreateIdempotent creates a new ShareRecord, but first checks if an identical active share already exists for the same researcher account with the same set of library IDs. If a match is found, it returns the existing share without creating a duplicate. The returned bool indicates whether an existing share was reused (true) or a new one was created (false).

func (*ShareStore) Extend

func (s *ShareStore) Extend(ctx context.Context, shareID string, duration time.Duration) (*model.ShareRecord, error)

Extend updates the expiresAt timestamp to now + duration after verifying the share is active. Returns ErrShareNotFound if the share doesn't exist, ErrShareAlreadyRevoked if revoked, or ErrShareExpired if the share has expired.

func (*ShareStore) FindMatchingActiveShare

func (s *ShareStore) FindMatchingActiveShare(ctx context.Context, researcherAccountID string, libraryIDs []string) (*model.ShareRecord, error)

FindMatchingActiveShare queries existing active shares for the given researcherAccountID and compares library ID sets (order-independent) for an exact match. If a match is found, it returns the existing ShareRecord. If no match exists, it returns nil.

func (*ShareStore) Get

func (s *ShareStore) Get(ctx context.Context, shareID string) (*model.ShareRecord, error)

Get retrieves a ShareRecord by its shareId.

func (*ShareStore) ListAll

func (s *ShareStore) ListAll(ctx context.Context) ([]*model.ShareRecord, error)

ListAll scans all ShareRecords and returns them ordered by createdAt descending. The scan is filtered to htsget shares, since the table also holds the other mechanism's records.

func (*ShareStore) ListByAccount

func (s *ShareStore) ListByAccount(ctx context.Context, researcherAccountID string) ([]*model.ShareRecord, error)

ListByAccount queries ShareRecords for a specific researcherAccountId using GSI2, ordered by createdAt descending.

The index is keyed on attributes both mechanisms write, so it covers both and the query is filtered down to htsget shares.

func (*ShareStore) Revoke

func (s *ShareStore) Revoke(ctx context.Context, shareID string) (*model.ShareRecord, error)

Revoke sets the revokedAt timestamp on a ShareRecord after verifying it is active. Returns ErrShareNotFound if the share doesn't exist, ErrShareAlreadyRevoked if already revoked, or ErrShareExpired if the share has expired.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL