From 36965ab471adddd48db50d5b2ee0c8e0aa3d9214 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonatan=20M=C3=A4nnchen?= Date: Thu, 5 Nov 2026 11:34:14 +0100 Subject: [PATCH 1/7] Document removal of Basic auth and API user management Co-Authored-By: Claude Opus 5.5 --- apiary.apib | 83 +++++----------------------------------------------- endpoints.md | 14 ++++----- 2 files changed, 14 insertions(+), 83 deletions(-) diff --git a/apiary.apib b/apiary.apib index bc077d7..25c4870 100644 --- a/apiary.apib +++ b/apiary.apib @@ -64,7 +64,7 @@ Most responses return an `ETag` header. Many responses will also return a `Last- ### Authentication -There are three ways to authenticate requests in the Hex API: OAuth2 tokens obtained via the Device Authorization Grant, API tokens, or Basic Authentication with a username and password. Failed authentication attempts will return `401 Unauthorized`. Resources accessed without proper authentication will return a `403 Forbidden` except for some resources that return `404 Not Found` to prevent leaking sensitive data. +There are two ways to authenticate requests in the Hex API: OAuth2 tokens and API tokens. Failed authentication attempts will return `401 Unauthorized`. Resources accessed without proper authentication will return a `403 Forbidden` except for some resources that return `404 Not Found` to prevent leaking sensitive data. Any endpoint implementation for Hex should support SSL termination by default, to prevent user credentials from being intercepted by third parties. @@ -84,13 +84,9 @@ $ curl -H "Authorization: token" https://hex.pm/api API tokens can be created via the web interface or the `/keys` endpoint. They provide direct access without the OAuth flow. -##### Basic Authentication (Deprecated) +##### Basic Authentication (Removed) -``` -$ curl -u "username" https://hex.pm/api -``` - -Basic authentication is deprecated and only allowed on some resources, specifically ones used to generate API tokens. This is because basic authentication is computationally expensive and less secure than using API tokens. New integrations should use OAuth2 Device Authorization instead. +The server does not accept Basic authentication. A request with Basic credentials gets `401 Unauthorized` with a message that Basic authentication is disabled. Clients should use OAuth2 Device Authorization instead. ### Two-Factor Authentication (2FA) @@ -194,52 +190,7 @@ Returns available API endpoints and documentation URL. Authenticated requests require a User account. A User is required to publish packages but not to consume packages from the package manager. -## Users collection [/users] - -### Create a User [POST] - -A successful user creation will send a confirmation email to the given email address. The email will contain a link to follow in order to confirm the email and activate the account. The account will be usable once activated. - -A user can be recreated for a given `username` and `email` if it has not been activated yet. - -API clients are required to include a text with a link to the [Hex Terms of Service](https://hex.pm/policies/termsofservice) that ensures users agree to the terms. If clients do not follow this requirement their access to the API may be limited. If using the API specification to sign up to non-official Hex services, this text is not required, but others services may have similar requirements. - -+ Request (application/json) - - + Attributes - + `username` (string, required) - Only allows any alphanumeric (`[A-Za-z0-9]`) and the following characters: `_-.`. Case insensitive. - + `password` (string, required) - Should simply be a printable UTF-8 string - + `email` (string, required) - Should be a valid email address - - + Header - - Accept: application/json - - + Body - - { - "username": "ericmj", - "password": "hunter42", - "email": "ericmj@mail.com" - } - -+ Response 201 (application/json) - - + Attributes (User) - - + Header - - Location: https://hex.pm/api/users/ericmj - - + Body - - { - "username": "ericmj", - "email": "ericmj@mail.com", - "inserted_at": "2015-04-05T01:21:49Z", - "updated_at": "2015-04-05T01:21:49Z", - "url": "https://hex.pm/api/users/ericmj" - } +The API does not create users or reset passwords. Users do this on the web interface. ## User [/users/{username_or_email}] @@ -373,27 +324,6 @@ Returns audit logs for the currently authenticated user. "inserted_at": "2015-04-05T01:21:49Z" }] -## Password reset [/users/{username_or_email}/reset] - -+ Parameters - + username_or_email: ericmj (string) - Can be either a username or the email address associated with a User - -### Reset User password [POST] - -Will start the process to reset a User's password. An email will be send to the User's primary email address containin a link to follow and will lead to a form where a new password can be chosen. - -+ Request (application/json) - - This request requires authentication. - - + Header - - Accept: application/json - Authorization: e2bfe5e65b9235acebe06df8027905c0 - -+ Response 204 (application/json) - # Group Repositories ## Repositories Collection [/repos] @@ -1448,7 +1378,7 @@ API Keys are used to authenticate requests (see Authentication section for more + Request - This request requires basic authentication and is allowed to be made even if the account email has not yet been confirmed. + This request requires an OAuth token from the Device Authorization Grant. It is allowed to be made even if the account email has not yet been confirmed. A user with two-factor authentication must send the `x-hex-otp` header. + Attributes + `name` (string, required) @@ -1458,7 +1388,8 @@ API Keys are used to authenticate requests (see Authentication section for more + Header Accept: application/json - Authorization: Basic ZXJpY21qOmh1bnRlcjQy + Authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9... + x-hex-otp: 123456 + Body diff --git a/endpoints.md b/endpoints.md index dff46ab..0ba61cf 100644 --- a/endpoints.md +++ b/endpoints.md @@ -118,7 +118,7 @@ Used by: `mix hex.owner`, `rebar3 hex owner`, `gleam owner` ### Authentication -**OAuth2 Device Authorization** (used by: `mix hex.user auth`, `gleam authenticate`): +**OAuth2 Device Authorization** (used by: `mix hex.user auth`, `rebar3 hex user auth`, `gleam authenticate`): | Type | Endpoint | Purpose | |------|----------|---------| @@ -127,11 +127,13 @@ Used by: `mix hex.owner`, `rebar3 hex owner`, `gleam owner` | API | `POST /oauth/revoke` | Revoke token | | API | `POST /oauth/revoke_by_hash` | Revoke token by hash | -**API Key Generation** (used by: `rebar3 hex user auth`): +**API Key Exchange** (used by: `mix hex.organization auth`): | Type | Endpoint | Purpose | |------|----------|---------| -| API | `POST /keys` | Create API key (with Basic Auth) | +| API | `POST /oauth/token` | Exchange an organization API key for a short-lived token (`grant_type=client_credentials`) | + +The API does not accept Basic authentication. ### API Key Management @@ -180,11 +182,9 @@ Used by: `mix hex.docs` ### User Management -Used by: `rebar3 hex user register`, `rebar3 hex user reset_password` - | Type | Endpoint | Purpose | |------|----------|---------| -| API | `POST /users` | Create new user account | | API | `GET /users/NAME` | Get user information | | API | `GET /users/me` | Get authenticated user | -| API | `POST /users/NAME/reset` | Request password reset | + +Users register and reset passwords on the web interface. The API does not support these actions. From d19514e8ce78eaafbe3c56f73a3f1ade57f082ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonatan=20M=C3=A4nnchen?= Date: Thu, 5 Nov 2026 11:34:15 +0100 Subject: [PATCH 2/7] Document API key permissions, format and management limits Co-Authored-By: Claude Opus 5.5 --- apiary.apib | 116 ++++++++++++++++++++++++++++++++++++++------------- endpoints.md | 2 +- 2 files changed, 87 insertions(+), 31 deletions(-) diff --git a/apiary.apib b/apiary.apib index 25c4870..15d8357 100644 --- a/apiary.apib +++ b/apiary.apib @@ -82,7 +82,7 @@ OAuth2 tokens are obtained via the [Device Authorization Grant (RFC 8628)](https $ curl -H "Authorization: token" https://hex.pm/api ``` -API tokens can be created via the web interface or the `/keys` endpoint. They provide direct access without the OAuth flow. +API tokens are created via the web interface or the `/keys` endpoint. They provide direct access without the OAuth flow. Clients must treat a token as an opaque string. Tokens differ in length and format, and new tokens start with `hex_`. ##### Basic Authentication (Removed) @@ -1335,6 +1335,24 @@ Also available under /repos/{repository} for packages belonging to a specific re API Keys are used to authenticate requests (see Authentication section for more details). A key has a name used to identify it and a secret that is used for the actual authentication. +Only a user who signed in can create or revoke keys. The request must authenticate with an OAuth token from the Device Authorization Grant. The server refuses API tokens and OAuth tokens from the Client Credentials Grant with `403 Forbidden`, so a leaked key cannot create keys that outlive it or revoke other keys. + +Each key has a list of permissions. A permission has a `domain` and, for some domains, a `resource`: + +| Domain | Resource | Allows | +|--------|----------|--------| +| `api` | none, `read`, or `write` | `read`: all API reads. `write` or none: all API actions, which includes all write domains below | +| `package` | `NAME` or `REPOSITORY/NAME` | Publish and change owners of one package, and all API reads | +| `publish` | none, `NAME`, or `REPOSITORY/NAME` | Publish, revert, retire, and unretire releases, and publish documentation. With a resource, only for that package | +| `owners` | none, `NAME`, or `REPOSITORY/NAME` | Add and remove package owners. With a resource, only for that package | +| `members` | none | Add, remove, and change the role of organization members | +| `administration` | none | Change the number of seats of an organization | +| `repository` | `ORGANIZATION` | Fetch from the private repository of the organization. Only for organization keys | +| `repositories` | none | Fetch from all private repositories the owner can access. Only for organization keys | +| `docs` | `ORGANIZATION` | Fetch private documentation of the organization | + +The server refuses the `keys` domain. A key is limited by what its owner can do when the key is used. For an organization key, the role of the member who creates the key also limits which permissions the key can get. + ## API Keys Collection [/keys] ### List all API Keys [GET] @@ -1357,6 +1375,7 @@ API Keys are used to authenticate requests (see Authentication section for more [{ "name": "my_computer", "authing_key": true, + "token_format": "v1", "permissions": [ { "domain": "api", @@ -1409,7 +1428,7 @@ API Keys are used to authenticate requests (see Authentication section for more The `secret` will be sent only once. It should be stored after creating the API key. Subsequent responses to GET requests will not include the `secret`. + Attributes (API Key) - + `secret` - The key secret, a 32 character hex encoded string + + `secret` - The key secret + Header @@ -1419,8 +1438,9 @@ API Keys are used to authenticate requests (see Authentication section for more { "name": "my_computer", - "secret": "e2bfe5e65b9235acebe06df8027905c0", + "secret": "hex_e2bfe5e65b9235acebe06df8027905c09a3b1c2d", "authing_key": false, + "token_format": "v2", "permissions": [ { "domain": "api", @@ -1439,38 +1459,28 @@ Removes all API keys for the authenticated user. + Request - This request requires authentication. + This request requires an OAuth token from the Device Authorization Grant. A user with two-factor authentication must send the `x-hex-otp` header. + Header - Authorization: e2bfe5e65b9235acebe06df8027905c0 + Authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9... + x-hex-otp: 123456 + Response 200 (application/json) - Returns the authing key. + + Body - + Attributes (API Key) + null + ++ Response 403 (application/json) + + The request authenticated with an API token. + Body { - "name": "my_computer", - "authing_key": true, - "permissions": [ - { - "domain": "api", - "resource": "write" - } - ], - "revoke_at": null, - "last_use": { - "ip": "192.168.1.1", - "user_agent": "Hex/2.0.0 (Elixir/1.14.0) (OTP/25.0)", - "used_at": "2014-04-21T18:00:00Z" - }, - "inserted_at": "2014-04-21T17:20:12Z", - "updated_at": "2014-04-21T17:20:12Z", - "url": "https://hex.pm/api/keys/my_computer" + "status": 403, + "message": "API keys cannot revoke API keys, revoke the key on https://hex.pm/dashboard/keys" } ## API Key [/keys/{name}] @@ -1483,6 +1493,10 @@ Removes all API keys for the authenticated user. + `name` (string, required) - Key name + `secret` (string, optional) - Only available immediately after creation, the user secret for the key + `authing_key` (boolean, required) - Whether this key is the one being used for the current request + + `token_format` (enum[string], required) - Format of the secret + + Members + + `v1` - 32 hex characters without a prefix + + `v2` - `hex_` prefix + `permissions` (array, required) - List of permissions the key has + (object) + `domain` (enum[string], required) - The domain of the permission @@ -1490,6 +1504,12 @@ Removes all API keys for the authenticated user. + `api` - Gives permission to actions on the API (can be specified with `resource` values `write` and `read`, default is `write`) + `repository` - Gives permission to actions on a specific repository specified in the `resource` + `repositories` - Gives permission to actions on all repositories the user has access to, the `resource` is omitted + + `package` - Gives permission to publish and change owners of the package specified in the `resource`, and to all API reads + + `publish` - Gives permission to publish, revert, retire, and unretire releases, optionally only for the package specified in the `resource` + + `owners` - Gives permission to add and remove package owners, optionally only for the package specified in the `resource` + + `members` - Gives permission to manage organization members, the `resource` is omitted + + `administration` - Gives permission to change the number of seats of an organization, the `resource` is omitted + + `docs` - Gives permission to fetch private documentation of the organization specified in the `resource` + `resource` (string, optional) + `revoke_at` (string, optional) - If set, the ISO8601-encoded timestamp when the key will be automatically revoked + `last_use` (object, optional) - Information about the last time this key was used @@ -1520,6 +1540,7 @@ Removes all API keys for the authenticated user. { "name": "my_computer", "authing_key": true, + "token_format": "v1", "permissions": [ { "domain": "api", @@ -1541,11 +1562,12 @@ Removes all API keys for the authenticated user. + Request - This request requires authentication. + This request requires an OAuth token from the Device Authorization Grant. The server refuses API tokens with `403 Forbidden`. A user with two-factor authentication must send the `x-hex-otp` header. + Header - Authorization: e2bfe5e65b9235acebe06df8027905c0 + Authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9... + x-hex-otp: 123456 + Response 200 (application/json) @@ -1558,6 +1580,7 @@ Removes all API keys for the authenticated user. { "name": "my_computer", "authing_key": false, + "token_format": "v1", "permissions": [ { "domain": "api", @@ -1595,6 +1618,7 @@ Removes all API keys for the authenticated user. [{ "name": "ci_server", "authing_key": false, + "token_format": "v1", "permissions": [ { "domain": "repository", @@ -1611,7 +1635,7 @@ Removes all API keys for the authenticated user. + Request - This request requires authentication. + This request requires an OAuth token from the Device Authorization Grant of a member of the organization. The server refuses API tokens with `403 Forbidden`. A user with two-factor authentication must send the `x-hex-otp` header. The role of the member limits which permissions the key can get. + Attributes + `name` (string, required) @@ -1621,7 +1645,8 @@ Removes all API keys for the authenticated user. + Header Accept: application/json - Authorization: e2bfe5e65b9235acebe06df8027905c0 + Authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9... + x-hex-otp: 123456 + Body @@ -1645,8 +1670,9 @@ Removes all API keys for the authenticated user. { "name": "ci_server", - "secret": "e2bfe5e65b9235acebe06df8027905c0", + "secret": "hex_e2bfe5e65b9235acebe06df8027905c09a3b1c2d", "authing_key": false, + "token_format": "v2", "permissions": [ { "domain": "repository", @@ -1697,7 +1723,7 @@ Creates a shortened URL. ### Verify Authentication [GET] -Verifies that the provided authentication token is valid and has the required permissions. +Verifies that the provided authentication token is valid and has the required permissions. The server answers `200 OK` with the key when the request authenticated with an API token, and `204 No Content` when it authenticated with an OAuth token. + Request @@ -1708,6 +1734,36 @@ Verifies that the provided authentication token is valid and has the required pe Accept: application/json Authorization: e2bfe5e65b9235acebe06df8027905c0 ++ Response 200 (application/json) + + Returned when the request authenticated with an API token. The `x-hex-key-id` header has the ID of the key. + + + Attributes + + `key` (object, required) + + `name` (string, required) - Key name + + `owner` (object, required) + + `type` (enum[string], required) + + Members + + `user` + + `organization` + + `name` (string, required) - Username or organization name + + + Header + + x-hex-key-id: 1234 + + + Body + + { + "key": { + "name": "ci_server", + "owner": { + "type": "organization", + "name": "acme" + } + } + } + + Response 204 + Response 401 (application/json) diff --git a/endpoints.md b/endpoints.md index 0ba61cf..d162f9f 100644 --- a/endpoints.md +++ b/endpoints.md @@ -148,7 +148,7 @@ Used by: `mix hex.organization key`, `rebar3 hex user key`, `rebar3 hex organiza | API | `DELETE /keys` | Delete all keys | | API | `GET /auth` | Test key permissions | -For organization keys, use `/orgs/ORG/keys` instead. +For organization keys, use `/orgs/ORG/keys` instead. Creating and deleting keys requires an OAuth token from the Device Authorization Grant. The API refuses API keys for these requests. ### Package Information From bc7cb14bc10807cf2d6f1e81018e183fbafb6874 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonatan=20M=C3=A4nnchen?= Date: Thu, 5 Nov 2026 11:34:15 +0100 Subject: [PATCH 3/7] Document Workload Identity Co-Authored-By: Claude Opus 5.5 --- apiary.apib | 113 +++++++++++++++++++++++++++++++++++++++++++++++++-- endpoints.md | 13 ++++++ 2 files changed, 122 insertions(+), 4 deletions(-) diff --git a/apiary.apib b/apiary.apib index 15d8357..f1eeead 100644 --- a/apiary.apib +++ b/apiary.apib @@ -74,7 +74,11 @@ Any endpoint implementation for Hex should support SSL termination by default, t $ curl -H "Authorization: Bearer token" https://hex.pm/api ``` -OAuth2 tokens are obtained via the [Device Authorization Grant (RFC 8628)](https://datatracker.ietf.org/doc/html/rfc8628). See the OAuth section below for details. OAuth2 tokens must be sent with the `Bearer` prefix in the `Authorization` header. OAuth tokens have read-only permissions by default; write operations require two-factor authentication via the `x-hex-otp` header. +OAuth2 tokens must be sent with the `Bearer` prefix in the `Authorization` header. The OAuth token endpoint issues them from three grants. See the OAuth section below for details. + + * The [Device Authorization Grant (RFC 8628)](https://datatracker.ietf.org/doc/html/rfc8628) issues a token for a person. These tokens have read-only permissions by default. Write operations require two-factor authentication via the `x-hex-otp` header. + * The Client Credentials Grant exchanges an API token for a short-lived token with the same permissions as the API token. This token cannot create or revoke API tokens. A token exchanged from the API token of a user requires the `x-hex-otp` header for write operations, the same as a Device Authorization Grant token. + * The [JWT Bearer Grant (RFC 7523)](https://www.rfc-editor.org/rfc/rfc7523) exchanges an OpenID Connect (OIDC) identity token from a CI provider for a short-lived token. See Workload Identity below. ##### API Token @@ -88,6 +92,23 @@ API tokens are created via the web interface or the `/keys` endpoint. They provi The server does not accept Basic authentication. A request with Basic credentials gets `401 Unauthorized` with a message that Basic authentication is disabled. Clients should use OAuth2 Device Authorization instead. +### Workload Identity + +Workload Identity lets a CI job publish or fetch packages without a stored API token. Hex.pm supports GitHub Actions as the only CI provider. + + 1. A package owner, or an organization admin, configures a workload identity on the web interface. It names a GitHub repository owner, one or more repositories, a workflow file, and optionally a GitHub environment. The server pins the immutable GitHub IDs of the owner and of each repository. + 2. The CI job requests an OIDC token from GitHub for the audience that the server expects. For Hex.pm, this audience is `hexpm`. Clients must use an audience they know in advance, not one that the server reports. See `GET /oidc/audience`. + 3. The CI job exchanges the OIDC token at `POST /oauth/token` with the JWT Bearer Grant and a scope. `package:REPOSITORY/PACKAGE` names one package to publish. `repository:ORGANIZATION` fetches from the private repository of an organization. + 4. The server verifies the OIDC token, finds a matching workload identity, and returns an access token. The access token expires after 15 minutes. + +A token with a package scope can only publish releases and documentation of that package, and read the staged releases of that package. It cannot revert or retire releases, or change owners, keys, members, or settings. A token with a repository scope can only fetch from the repository endpoint. + +The server accepts each OIDC token only once. It refuses OIDC tokens that are valid for more than 15 minutes. It refuses OIDC tokens from `pull_request_target` and `workflow_run` events, because a pull request from a fork can trigger these events. A workload identity that names a public GitHub repository must also name a GitHub environment. + +A workload identity cannot create a public package. An organization workload identity can create a package in the private repository of its organization. + +Releases that a workload identity publishes include the verified OIDC claims in the `oidc_claims` field of the release. + ### Two-Factor Authentication (2FA) Write operations may require two-factor authentication. When 2FA is required, the server will respond with `403 Forbidden` and a message indicating that a one-time password is needed. The client should then retry the request with the `x-hex-otp` header containing the TOTP code. @@ -918,6 +939,23 @@ Also available under /repos/{repository} for packages belonging to a specific re + `username` (string, required) + `email` (string, optional) + `url` (string, required) + + `oidc_claims` (object, optional) - Verified OIDC claims of the CI job that published this release with a workload identity. `null` if a workload identity did not publish the release. All values are strings copied from the GitHub Actions OIDC token. + + `repository` (string) - GitHub repository as `owner/name` + + `repository_id` (string) - Immutable GitHub repository ID + + `repository_owner` (string) - GitHub repository owner login + + `repository_owner_id` (string) - Immutable GitHub owner ID + + `workflow_ref` (string) - Workflow file and Git ref, for example `owner/name/.github/workflows/release.yml@refs/tags/v0.4.1` + + `job_workflow_ref` (string) - Workflow file and Git ref of the job, which is different from `workflow_ref` for a reusable workflow + + `environment` (string, optional) - GitHub Actions environment + + `sha` (string) - Git commit SHA + + `ref` (string) - Git ref + + `ref_type` (string) - `branch` or `tag` + + `run_id` (string) - GitHub Actions run ID + + `run_number` (string) - GitHub Actions run number + + `run_attempt` (string) - GitHub Actions run attempt + + `actor` (string) - GitHub login that triggered the workflow run + + `actor_id` (string) - Immutable GitHub ID of the actor + + `event_name` (string) - GitHub event that triggered the workflow run + `downloads` (number, required) - Number of downloads of the release + `inserted_at` (string, required) - ISO8601-encoded timestamp + `updated_at` (string, required) - ISO8601-encoded timestamp @@ -992,6 +1030,7 @@ Also available under /repos/{repository} for packages belonging to a specific re "email": "ericmj@mail.com", "url": "https://hex.pm/api/users/ericmj" }, + "oidc_claims": null, "downloads": 16, "security_advisories": [{ "id": "GHSA-xxxx-yyyy-zzzz", @@ -1080,6 +1119,7 @@ Will also create a new package or update an existing one. See the package tarbal "email": "ericmj@mail.com", "url": "https://hex.pm/api/users/ericmj" }, + "oidc_claims": null, "downloads": 0, "inserted_at": "2014-04-23T18:58:54Z", "updated_at": "2014-04-23T18:58:54Z" @@ -1781,6 +1821,8 @@ Verifies that the provided authentication token is valid and has the required pe OAuth2 Device Authorization Grant ([RFC 8628](https://datatracker.ietf.org/doc/html/rfc8628)) enables CLI tools to authenticate users without requiring them to enter credentials directly into the terminal. Instead, users authenticate via a web browser. +The OAuth endpoints read the client and the grant from the request body. They ignore a refused credential in the `Authorization` header. + ## Device Authorization [/oauth/device_authorization] ### Initiate Device Authorization [POST] @@ -1829,13 +1871,21 @@ Exchanges credentials for access and refresh tokens. Supports multiple grant typ **Refresh Token Grant** (`grant_type=refresh_token`): Exchanges a refresh token for a new access token. +**Client Credentials Grant** (`grant_type=client_credentials`): Exchanges an API token, sent as `client_secret`, for a short-lived access token. The access token has the permissions of the API token, limited by `scope`. The response has no refresh token. + +**JWT Bearer Grant** (`grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer`, [RFC 7523](https://www.rfc-editor.org/rfc/rfc7523)): Exchanges a GitHub Actions OIDC token, sent as `assertion`, for a workload identity access token. No `client_id` is needed, because the OIDC token is the credential. `scope` is required and names one target: `package:REPOSITORY/PACKAGE` to publish one package, or `repository:ORGANIZATION` to fetch from the private repository of an organization. The access token expires after 900 seconds and has no refresh token. See the Workload Identity section in the introduction. The server answers `400` with `unsupported_grant_type` when the deployment disables Workload Identity. + + Request (application/x-www-form-urlencoded) + Attributes - + `grant_type` (string, required) - Grant type: `urn:ietf:params:oauth:grant-type:device_code` or `refresh_token` - + `client_id` (string, required) - The OAuth client identifier + + `grant_type` (string, required) - Grant type: `urn:ietf:params:oauth:grant-type:device_code`, `refresh_token`, `client_credentials`, or `urn:ietf:params:oauth:grant-type:jwt-bearer` + + `client_id` (string, optional) - The OAuth client identifier. Required for all grants except the JWT Bearer Grant + `device_code` (string, optional) - Required for device_code grant + `refresh_token` (string, optional) - Required for refresh_token grant + + `client_secret` (string, optional) - Required for client_credentials grant. The API token to exchange + + `assertion` (string, optional) - Required for jwt-bearer grant. The OIDC token from the CI provider + + `scope` (string, optional) - Space-separated list of requested scopes. Required for jwt-bearer grant + + `name` (string, optional) - A descriptive name for the token, for the client_credentials grant + Body @@ -1873,7 +1923,11 @@ Exchanges credentials for access and refresh tokens. Supports multiple grant typ + `slow_down` - Client is polling too frequently, increase interval + `access_denied` - User denied the authorization request + `expired_token` - The device code has expired - + `invalid_grant` - Invalid or malformed device code or refresh token + + `invalid_grant` - Invalid or malformed device code, refresh token, or OIDC token, or an OIDC token that was already exchanged + + `invalid_request` - A required parameter is missing + + `invalid_scope` - The scope is missing or malformed + + `invalid_client` - The client or the API token is not valid + + `unsupported_grant_type` - The grant type is not supported + `error_description` (string, required) - Human-readable error description + Body @@ -1883,6 +1937,28 @@ Exchanges credentials for access and refresh tokens. Supports multiple grant typ "error_description": "Authorization pending" } ++ Response 403 (application/json) + + Returned for the JWT Bearer Grant when no workload identity matches the OIDC token and the scope. The server gives the same answer for a package, repository, or organization that does not exist. + + + Body + + { + "error": "access_denied", + "error_description": "No matching workload identity" + } + ++ Response 429 (application/json) + + Returned for the JWT Bearer Grant when there were too many exchanges from the address, or too many failed exchanges for the GitHub repository. For the GitHub repository limit, `error` is `slow_down`. + + + Body + + { + "error": "slow_down", + "error_description": "Too many failed mint requests. Please try again later." + } + ## Token Revocation [/oauth/revoke] ### Revoke Token [POST] @@ -1929,3 +2005,32 @@ Revokes a token using the refresh token hash. This allows revocation when the ac + Body {} + +# Group OIDC + +## OIDC Audience [/oidc/audience] + +### Fetch OIDC Audience [GET] + +Returns the audience that the server expects in OIDC tokens for the JWT Bearer Grant. The server answers `404 Not Found` when the deployment disables Workload Identity. + +Clients must not request an OIDC token for the audience that this endpoint returns. A CI provider issues a token for any audience that the job asks for. A server that is not Hex.pm could return the audience of another service, such as another package registry or a cloud provider. The client would then send that server a token that the other service accepts. + +Clients must use a configured audience, `hexpm` by default. Clients use this endpoint only to check that the server expects the same audience. If the values are different, the client must stop and not request an OIDC token. + ++ Request + + + Header + + Accept: application/json + ++ Response 200 (application/json) + + + Attributes + + `audience` (string, required) + + + Body + + { + "audience": "hexpm" + } diff --git a/endpoints.md b/endpoints.md index d162f9f..589b083 100644 --- a/endpoints.md +++ b/endpoints.md @@ -96,6 +96,19 @@ Used by: `mix hex.publish`, `rebar3 hex publish`, `gleam publish` | API | `GET /users/me` | Get current user (for new packages) | | API | `PUT /packages/NAME/owners/USERNAME` | Add first owner (for new packages) | +### Publishing from CI with Workload Identity + +Used by: `mix hex.publish`, `rebar3 hex publish` in GitHub Actions + +| Type | Endpoint | Purpose | +|------|----------|---------| +| API | `GET /oidc/audience` | Check that the server expects the configured audience (`hexpm` by default) before requesting the GitHub Actions OIDC token | +| API | `POST /oauth/token` | Exchange the OIDC token with the JWT Bearer Grant (`scope=package:REPOSITORY/PACKAGE`) | +| API | `POST /publish` | Publish with `Authorization: Bearer TOKEN` | +| API | `POST /oauth/revoke` | Revoke the token before it expires (optional) | + +To fetch from a private repository, exchange with `scope=repository:ORGANIZATION` and send the token to the repository endpoint. + ### Package Retirement Used by: `mix hex.retire`, `rebar3 hex retire`, `gleam retire` From 7033b6b89147e4345f25d58e7ba0c46444093daa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonatan=20M=C3=A4nnchen?= Date: Thu, 5 Nov 2026 11:49:22 +0100 Subject: [PATCH 4/7] Document staged publishing Co-Authored-By: Claude Opus 5.5 --- apiary.apib | 140 ++++++++++++++++++++++++++++++++++++++++++++++++++- endpoints.md | 4 ++ 2 files changed, 143 insertions(+), 1 deletion(-) diff --git a/apiary.apib b/apiary.apib index f1eeead..aa2623b 100644 --- a/apiary.apib +++ b/apiary.apib @@ -109,6 +109,20 @@ A workload identity cannot create a public package. An organization workload ide Releases that a workload identity publishes include the verified OIDC claims in the `oidc_claims` field of the release. +### Staged Publishing + +Staged publishing holds a release or its documentation until a person approves it. When staged publishing applies, the server stores the upload as a staged release and does not publish it. A package maintainer with two-factor authentication approves or rejects the staged release on the web interface. A staged release expires after seven days. The API does not approve or reject staged releases. + +Staged publishing applies to uploads that authenticate with an API token, with an OAuth token exchanged from an organization API token, or with a workload identity token. It does not apply to uploads that authenticate with an OAuth token for a user and an `x-hex-otp` code. Where the deployment enables the feature, it applies when one of these conditions is true: + + * The package has staged publishing enabled. New packages have it enabled by default. + * The organization that owns the private repository requires it for all of its packages. + * The registry operators enabled emergency publishing mode. In this mode, staged publishing applies to all releases and documentation of public packages. + +When staged publishing applies, an API token cannot revert a release or its documentation. The server answers `403 Forbidden`. + +Clients find a staged upload by its response from the publish endpoints. The response has the `Staged Release` attributes, and the `Location` header has the URL of the staged release resource. Clients can poll that URL until the `status` is no longer `staged`. + ### Two-Factor Authentication (2FA) Write operations may require two-factor authentication. When 2FA is required, the server will respond with `403 Forbidden` and a message indicating that a one-time password is needed. The client should then retry the request with the `x-hex-otp` header containing the TOTP code. @@ -1053,7 +1067,7 @@ Also available under /repos/{repository} for packages belonging to a specific re ### Revert a Release [DELETE] -Reverts (deletes) a release. This is only allowed within one hour of publishing. +Reverts (deletes) a release. This is only allowed within one hour of publishing. A workload identity token cannot revert a release. + Request @@ -1065,12 +1079,27 @@ Reverts (deletes) a release. This is only allowed within one hour of publishing. + Response 204 ++ Response 403 (application/json) + + Staged publishing applies to the package and the request authenticated with an API token. See the Staged Publishing section. + + + Body + + { + "status": 403, + "message": "This package uses staged publishing, so API keys can't revert it. Revert with your Hex account and a two-factor code." + } + ## Publishing Releases [/publish] ### Publish a Release [POST] Will also create a new package or update an existing one. See the package tarball specification for details about the request contents. +Also available under /repos/{repository} for packages belonging to a specific repository. + +The request can authenticate with a workload identity token. When staged publishing applies, the server does not publish the release. It answers `201 Created` with the `Staged Release` attributes instead of the `Release` attributes. See the Staged Publishing section. + + Request This request requires authentication. @@ -1125,6 +1154,111 @@ Will also create a new package or update an existing one. See the package tarbal "updated_at": "2014-04-23T18:58:54Z" } +## Staged Release [/packages/{name}/releases/{version}/staged] + +A release that waits for approval. See the Staged Publishing section. + +Also available under /repos/{repository} for packages belonging to a specific repository. + ++ Parameters + + name: plug (string) + Package name + + version: 0.4.1 (string) + Release version + ++ Attributes + + `name` (string, required) - Package name + + `version` (string, required) - Release version + + `kind` (enum[string], required) - What waits for approval + + Members + + `release` - A release, which can include its documentation + + `docs` - Documentation for a release + + `status` (enum[string], required) + + Members + + `staged` - Waits for approval + + `approved` - A person approved it and the server published it + + `rejected` - A person rejected it + + `expired` - Nobody approved it before `expires_at` + + `checksum` (string, required) - SHA-256 checksum of the uploaded tarball, hex-encoded (lowercase). For `kind` `release`, this is the outer checksum of the package tarball. For `kind` `docs`, this is the checksum of the documentation tarball. A client can show it so that the person who approves can compare it with the checksum on the web interface. + + `approval_checksum` (string, required) - Identifies the exact content of the staged release and the credential that staged it. The value changes when the package tarball, the documentation attached to the staged release, or the credential changes. The server refuses an approval or rejection made for an older value, so a person cannot approve content that changed after they reviewed it. A client that polls this resource can compare the value with the one from the publish response to detect that the release was staged again. Clients must treat the value as opaque. + + `expires_at` (string, required) - ISO8601-encoded timestamp + + `url` (string, required) - URL of this resource + + `html_url` (string, required) - URL of the approval page on the web interface + +### Fetch a Staged Release [GET] + +The request must authenticate with the credential that staged the release, or as a user who can approve it. The server answers `404 Not Found` to other callers. After approval, rejection, or expiry, the resource stays available with the final `status`. + ++ Request + + This request requires authentication. + + + Header + + Accept: application/json + Authorization: e2bfe5e65b9235acebe06df8027905c0 + ++ Response 200 (application/json) + + + Attributes (Staged Release) + + + Body + + { + "name": "plug", + "version": "0.4.1", + "kind": "release", + "status": "staged", + "checksum": "abc123def456...", + "approval_checksum": "abc123...", + "expires_at": "2014-04-30T18:58:54Z", + "url": "https://hex.pm/api/packages/plug/releases/0.4.1/staged", + "html_url": "https://hex.pm/dashboard/staged-releases/hexpm/plug/0.4.1" + } + +## Staged Release Documentation [/packages/{name}/releases/{version}/docs/staged] + +Documentation that waits for approval. The resource has the `Staged Release` attributes with `kind` `docs`. + +Also available under /repos/{repository} for packages belonging to a specific repository. + ++ Parameters + + name: plug (string) + Package name + + version: 0.4.1 (string) + Release version + +### Fetch Staged Documentation [GET] + +The same rules as for Fetch a Staged Release apply. + ++ Request + + This request requires authentication. + + + Header + + Accept: application/json + Authorization: e2bfe5e65b9235acebe06df8027905c0 + ++ Response 200 (application/json) + + + Attributes (Staged Release) + + + Body + + { + "name": "plug", + "version": "0.4.1", + "kind": "docs", + "status": "staged", + "checksum": "abc123def456...", + "approval_checksum": "abc123...", + "expires_at": "2014-04-30T18:58:54Z", + "url": "https://hex.pm/api/packages/plug/releases/0.4.1/docs/staged", + "html_url": "https://hex.pm/dashboard/staged-releases/hexpm/plug/0.4.1/docs" + } + ## Retiring Releases [/packages/{name}/releases/{version}/retire] Also available under /repos/{repository} for packages belonging to a specific repository. @@ -1230,6 +1364,8 @@ The uploaded tarball will be served under https://repo.hex.pm/docs/{package}-{ve The tarball contents will be served at http://hexdocs.pm/{package}/{version}. The latest upload will be served at http://hexdocs.pm/{package}. +The request can authenticate with a workload identity token. When staged publishing applies, or the release is itself a staged release, the server does not publish the documentation. It answers `201 Created` with the `Staged Release` attributes and `kind` `docs`, and the `Location` header has the URL of the staged documentation. See the Staged Publishing section. + + Request This request requires authentication. @@ -1248,6 +1384,8 @@ The tarball contents will be served at http://hexdocs.pm/{package}/{version}. Th ### Remove Package Documentation [DELETE] +A workload identity token cannot remove documentation. When staged publishing applies to the package, an API token cannot remove documentation, and the server answers `403 Forbidden`. + + Response 204 # Group Package Owners diff --git a/endpoints.md b/endpoints.md index 589b083..e8ee870 100644 --- a/endpoints.md +++ b/endpoints.md @@ -95,6 +95,10 @@ Used by: `mix hex.publish`, `rebar3 hex publish`, `gleam publish` | API | `GET /packages/NAME` | Check if package exists | | API | `GET /users/me` | Get current user (for new packages) | | API | `PUT /packages/NAME/owners/USERNAME` | Add first owner (for new packages) | +| API | `GET /packages/NAME/releases/VERSION/staged` | Poll a staged release until a person approves it | +| API | `GET /packages/NAME/releases/VERSION/docs/staged` | Poll staged documentation until a person approves it | + +When staged publishing applies (see the Staged Publishing section of the HTTP API), the publish endpoints answer with a staged release instead of a release. The `Location` header has the URL to poll. ### Publishing from CI with Workload Identity From 3ed25ef6068ba65eb4f2522bcf3b4d17f243596f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonatan=20M=C3=A4nnchen?= Date: Thu, 5 Nov 2026 11:49:22 +0100 Subject: [PATCH 5/7] Document retire-all, member invitations and organization SSO authorization Co-Authored-By: Claude Opus 5.5 --- apiary.apib | 120 ++++++++++++++++++++++++++++++++++++++++++++++++++- endpoints.md | 2 + 2 files changed, 121 insertions(+), 1 deletion(-) diff --git a/apiary.apib b/apiary.apib index aa2623b..9f38aec 100644 --- a/apiary.apib +++ b/apiary.apib @@ -203,6 +203,7 @@ Returns available API endpoints and documentation URL. + Attributes + `packages_url` (string, required) - URL template for packages collection + `package_url` (string, required) - URL template for a single package + + `package_retirement_url` (string, required) - URL template to retire all releases of a package + `package_release_url` (string, required) - URL template for a package release + `package_owners_url` (string, required) - URL template for package owners + `keys_url` (string, required) - URL for API keys collection @@ -214,6 +215,7 @@ Returns available API endpoints and documentation URL. { "packages_url": "https://hex.pm/api/packages", "package_url": "https://hex.pm/api/packages/{name}", + "package_retirement_url": "https://hex.pm/api/packages/{name}/retire", "package_release_url": "https://hex.pm/api/packages/{name}/releases/{version}", "package_owners_url": "https://hex.pm/api/packages/{name}/owners", "keys_url": "https://hex.pm/api/keys", @@ -595,7 +597,35 @@ Returns audit logs for the organization. "role": "write" } -+ Response 204 ++ Response 202 (application/json) + + The server sends an invitation to the user. The user becomes a member when they accept the invitation. This request requires the credentials of a user. An organization API token cannot invite members. + + + Attributes + + `username` (string, required) + + `url` (string, required) + + `role` (string, required) - Role the user gets when they accept the invitation + + `expires_at` (string, required) - ISO8601-encoded timestamp when the invitation expires + + + Body + + { + "username": "newmember", + "url": "https://hex.pm/api/users/newmember", + "role": "write", + "expires_at": "2017-09-06T17:35:23Z" + } + ++ Response 429 (application/json) + + The organization invited this user in the last 24 hours, or too many invitations were sent to this user or by the inviting user recently. + + + Body + + { + "status": 429, + "message": "this organization can invite this user once every 24 hours" + } ## Organization Member [/orgs/{name}/members/{username}] @@ -1259,6 +1289,46 @@ The same rules as for Fetch a Staged Release apply. "html_url": "https://hex.pm/dashboard/staged-releases/hexpm/plug/0.4.1/docs" } +## Retiring All Releases [/packages/{name}/retire] + +Also available under /repos/{repository} for packages belonging to a specific repository. + ++ Parameters + + name: plug (string) + Package name + +### Mark All Releases as Retired [POST] + ++ Request + + This request requires authentication. + + Marks all releases of the package as retired. By default, the server does not change releases that are already retired. + + + Attributes + + `reason` (enum[string], required) - Reason for retiring the releases + + Members + + `other` + + `invalid` + + `security` + + `deprecated` + + `renamed` + + `message` (string, optional) - An additional, clarifying message for the retirement + + `replace` (boolean, optional) - If `true`, also replace the retirement of releases that are already retired. Default: `false` + + + Header + + Authorization: e2bfe5e65b9235acebe06df8027905c0 + + + Body + + { + "reason": "deprecated", + "message": "This package has been deprecated in favor of ecto." + } + ++ Response 204 + ## Retiring Releases [/packages/{name}/releases/{version}/retire] Also available under /repos/{repository} for packages belonging to a specific repository. @@ -2039,6 +2109,7 @@ Exchanges credentials for access and refresh tokens. Supports multiple grant typ + `token_type` (string, required) - Always "Bearer" + `expires_in` (number, required) - Access token lifetime in seconds + `scope` (string, required) - Space-separated list of granted scopes + + `organization_reauth_required` (array[string], optional) - Organizations that require single sign-on, for which the token did not get access. The client must authorize these organizations again with `POST /oauth/organization_authorization` + Body @@ -2144,6 +2215,53 @@ Revokes a token using the refresh token hash. This allows revocation when the ac {} +## Organization Authorization [/oauth/organization_authorization] + +### Request Organization Authorization [POST] + +Starts single sign-on for organizations that require it. Use it when a token response lists organizations in `organization_reauth_required`. The user opens `verification_uri` in a browser and signs in with the identity provider of each organization. The next refresh of the token then gets access to these organizations. + ++ Request (application/json) + + This request requires an OAuth token from the Device Authorization Grant. The server refuses API tokens and tokens from the Client Credentials Grant. + + + Attributes + + `organizations` (array[string], required) - Names of the organizations to authorize + + + Header + + Authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9... + + + Body + + { + "organizations": ["acme"] + } + ++ Response 201 (application/json) + + + Attributes + + `verification_uri` (string, required) - URL that the user opens in a browser + + `expires_in` (number, required) - Seconds until the URL expires + + + Body + + { + "verification_uri": "https://hex.pm/organizations/authorize?code=abc123", + "expires_in": 600 + } + ++ Response 422 (application/json) + + None of the organizations require single sign-on for this user, or the request did not authenticate with a Device Authorization Grant token. The server gives the same answer for an organization that does not exist, one the user is not a member of, and one that does not require single sign-on. + + + Body + + { + "status": 422, + "message": "Organization authentication is not required for the requested organizations" + } + # Group OIDC ## OIDC Audience [/oidc/audience] diff --git a/endpoints.md b/endpoints.md index e8ee870..ef74fc8 100644 --- a/endpoints.md +++ b/endpoints.md @@ -119,6 +119,7 @@ Used by: `mix hex.retire`, `rebar3 hex retire`, `gleam retire` | Type | Endpoint | Purpose | |------|----------|---------| +| API | `POST /packages/NAME/retire` | Retire all releases | | API | `POST /packages/NAME/releases/VERSION/retire` | Retire a release | | API | `DELETE /packages/NAME/releases/VERSION/retire` | Unretire a release | @@ -143,6 +144,7 @@ Used by: `mix hex.owner`, `rebar3 hex owner`, `gleam owner` | API | `POST /oauth/token` | Poll for token / refresh token | | API | `POST /oauth/revoke` | Revoke token | | API | `POST /oauth/revoke_by_hash` | Revoke token by hash | +| API | `POST /oauth/organization_authorization` | Sign in to organizations that require single sign-on | **API Key Exchange** (used by: `mix hex.organization auth`): From 2e371124f22c86cea895d0df20260f2a32104de0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonatan=20M=C3=A4nnchen?= Date: Thu, 5 Nov 2026 11:49:22 +0100 Subject: [PATCH 6/7] Update threat model for Workload Identity and staged publishing Co-Authored-By: Claude Opus 5.5 --- security/threat-model/actors.md | 22 ++++-- security/threat-model/architecture.md | 24 ++++-- security/threat-model/assets.md | 13 +++- security/threat-model/assumptions.md | 16 +++- security/threat-model/client-flows.md | 103 +++++++++++++++++++++++--- security/threat-model/mitigations.md | 59 ++++++++++++--- security/threat-model/overview.md | 2 +- security/threat-model/threats.md | 14 +++- 8 files changed, 218 insertions(+), 35 deletions(-) diff --git a/security/threat-model/actors.md b/security/threat-model/actors.md index 9f0dceb..e28b93f 100644 --- a/security/threat-model/actors.md +++ b/security/threat-model/actors.md @@ -12,7 +12,7 @@ Developers and CI/CD systems that install and use packages. | Attribute | Description | |-----------|-------------| -| Access | Unauthenticated read access to public packages; API key for private | +| Access | Unauthenticated read access to public packages. API key, OAuth token, or workload identity token for private packages | | Trust level | Untrusted (no write access) | | Capabilities | Download packages, read registry metadata, view documentation | @@ -21,13 +21,25 @@ Developers and CI/CD systems that install and use packages. Developers who publish and manage packages. There are two ownership levels: - **Maintainer** — publish, retire/unretire releases, upload documentation -- **Owner** — all maintainer capabilities, plus manage package ownership +- **Owner** — all maintainer capabilities, plus manage package ownership, workload identities, and staged publishing settings + +A maintainer with 2FA approves or rejects staged releases. | Attribute | Description | |-----------|-------------| | Access | Authenticated API access, publishing permissions | | Trust level | Trusted for their own packages | +### CI Workload + +A GitHub Actions job that authenticates with a workload identity instead of a stored API key. + +| Attribute | Description | +|-----------|-------------| +| Access | Short-lived token from an OIDC token exchange, scoped to one package or one organization repository | +| Trust level | Trusted for the package or repository that the workload identity covers | +| Capabilities | Publish releases and documentation, or fetch from a private repository. Cannot revert, retire, or change owners, keys, members, or settings | + ### Organization Administrator Manages private repositories and teams within an organization. @@ -36,7 +48,7 @@ Manages private repositories and teams within an organization. |-----------|-------------| | Access | Elevated permissions within organization scope | | Trust level | Trusted for organization resources | -| Capabilities | Manage members, configure billing, access private packages | +| Capabilities | Manage members, configure billing, access private packages, configure organization workload identities, require staged publishing for the private repository | ### Hex.pm Operator @@ -46,7 +58,7 @@ Maintains and operates the registry infrastructure. |-----------|-------------| | Access | Infrastructure and administrative access | | Trust level | Highly trusted | -| Capabilities | System administration, incident response, policy enforcement | +| Capabilities | System administration, incident response, policy enforcement, emergency publishing mode | ## Adversarial Actors @@ -80,7 +92,7 @@ Maintains and operates the registry infrastructure. |-----------|-------------| | Goal | Compromise build/release pipeline | | Access | Indirect via dependencies or tooling | -| Capabilities | Compromise CI systems, tamper with build artifacts, inject backdoors via dependencies | +| Capabilities | Compromise CI systems, tamper with build artifacts, inject backdoors via dependencies, run a workflow that matches a workload identity | ### Insider Threat diff --git a/security/threat-model/architecture.md b/security/threat-model/architecture.md index aee5512..d3fe589 100644 --- a/security/threat-model/architecture.md +++ b/security/threat-model/architecture.md @@ -50,17 +50,17 @@ C4Context System_Ext(fastly, "Fastly CDN", "Global content delivery and edge compute") System_Ext(storage, "Cloud Storage", "Package artifacts and registry files") - System_Ext(github, "GitHub", "OAuth authentication and source code hosting") + System_Ext(github, "GitHub", "OAuth authentication, source code hosting, and Actions OIDC issuer") System_Ext(email, "Email Service", "Sends notifications and password resets") Rel(consumer, hex, "API requests", "HTTPS") Rel(consumer, fastly, "Repository requests", "HTTPS") - Rel(maintainer, hex, "Publishes packages", "HTTPS + API Key") + Rel(maintainer, hex, "Publishes packages", "HTTPS + OAuth, API Key, or Workload Identity") Rel(operator, hex, "Administers", "Internal") Rel(fastly, storage, "Serves registry + tarballs", "HTTPS cached") - Rel(hex, github, "OAuth authentication") + Rel(hex, github, "OAuth authentication, OIDC key and repository lookups") Rel(hex, email, "Sends notifications") Rel(hex, storage, "Stores packages") @@ -74,7 +74,7 @@ C4Context - **Hex.pm Operators** - Maintain and operate the registry infrastructure **External Systems:** -- **GitHub** provides OAuth authentication and hosts package source code +- **GitHub** provides OAuth authentication, hosts package source code, and issues the OIDC tokens that GitHub Actions jobs exchange for workload identity tokens - **Email Service** sends password resets, ownership notifications, etc. - **Fastly CDN** caches and delivers registry files and package tarballs globally @@ -273,6 +273,12 @@ C4Context - **Controls**: Signed registry, checksums, signature verification - **Critical**: Clients must NEVER send credentials to untrusted mirrors +### Boundary 2a: CI Provider to Registry API + +- **Crosses**: GitHub Actions OIDC tokens, workload identity tokens +- **Controls**: OIDC signature verification against GitHub's keys, audience check, single-use `jti`, refusal of privileged triggers, match against pinned GitHub IDs, workflow, and environment, 15 minute token lifetime, staged publishing +- **Critical**: Hex.pm trusts GitHub to issue OIDC tokens only to the workflow runs that the claims describe + ### Boundary 3: Internal Services - **Crosses**: Database connections, internal APIs @@ -289,7 +295,8 @@ C4Context |------|----------|--------|----------------|-----------| | Client → Registry files | HTTPS | Protobuf + gzip | None (public) or API key (private) or OAuth2 (private) | RSA-PKCS1-SHA512 signatures | | Client → Tarballs | HTTPS | tar | None (public) or API key (private) or OAuth2 (private) | Checksums | -| Client → API | HTTPS | JSON | API key (Bearer token) or OAuth | TLS | +| Client → API | HTTPS | JSON | API key or OAuth access token (Bearer). OAuth access tokens come from the device code, client credentials, or JWT Bearer grant | TLS | +| CI job → API (token exchange) | HTTPS | Form + JSON | GitHub Actions OIDC token as the JWT Bearer Grant assertion | TLS | | Browser → Web | HTTPS | HTML | Session cookie | TLS | | Browser → Docs | HTTPS | HTML | None | TLS + CSP | | hex.pm → PostgreSQL | TCP | PostgreSQL protocol | Connection credentials | - | @@ -308,8 +315,13 @@ sequenceDiagram participant Worker as Registry Builder participant CDN as Fastly CDN - Client->>API: Publish package (Bearer: API key or OAuth access token; OAuth tokens additionally require x-hex-otp) + Client->>API: Publish package (Bearer: API key or OAuth access token, user OAuth tokens also require x-hex-otp) API->>API: Validate authentication & authorization + opt Staged publishing applies (API key, organization key token, or workload identity) + API->>DB: Store staged release + API-->>Client: 201 Created (staged release) + Note over API: A maintainer with 2FA approves on the dashboard, then the flow below continues + end API->>DB: Store package metadata API->>S3: Upload tarball API->>Worker: Trigger registry rebuild diff --git a/security/threat-model/assets.md b/security/threat-model/assets.md index 49d49e6..90eb9fa 100644 --- a/security/threat-model/assets.md +++ b/security/threat-model/assets.md @@ -54,7 +54,17 @@ Bearer tokens for API access. |-----------|-------------| | Location | Database (hashed), client machines (plaintext/encrypted) | | Impact if compromised | Unauthorized actions within token scope | -| Protection | Scoping, revocation, short-lived OAuth tokens | +| Protection | Scoping, revocation, short-lived OAuth and workload identity tokens, `hex_` prefix for secret scanning, staged publishing | + +### Workload Identity Configuration + +The GitHub owner, repositories, workflow, and environment that a package or organization trusts to publish or fetch. + +| Attribute | Description | +|-----------|-------------| +| Location | Database | +| Impact if compromised | An attacker-controlled workflow can publish the covered packages or fetch private packages | +| Protection | Full ownership or organization admin role with 2FA to change, pinned GitHub IDs, email notifications, audit log | ## High Value Assets @@ -134,6 +144,7 @@ Impact ratings use [CVSS v4.0](https://www.first.org/cvss/v4.0/specification-doc | Registry Signing Key | High | High | High | | Maintainer Accounts | High | High | Low | | API Tokens | High | High | Low | +| Workload Identity Configuration | Low | High | Low | | Documentation Content | None | Low | Low | | Package Ownership | Low | High | Low | | Organization Data | High | High | Low | diff --git a/security/threat-model/assumptions.md b/security/threat-model/assumptions.md index 705989d..342d3a2 100644 --- a/security/threat-model/assumptions.md +++ b/security/threat-model/assumptions.md @@ -13,6 +13,9 @@ For controls that address threats under these assumptions, see [Mitigations](mit | Development environments may be compromised | Build provenance cannot be guaranteed without attestations | | Maintainers are responsible for their package security | Registry does not audit package contents | | Maintainers may make mistakes | Leaked credential detection, but cannot prevent all exposures | +| CI jobs send OIDC tokens only to a trusted Hex API URL | A server at an untrusted URL receives a valid `hexpm` token and can use it at hex.pm before it expires. Clients pin the audience so the server cannot get a token for another service | +| Maintainers protect the GitHub workflows that their workload identities trust | Hex.pm cannot see GitHub branch protection or environment protection rules. Anyone who can run a matching workflow can publish | +| Maintainers review a staged release before they approve it | Approval checks that a person agreed, not that the content is safe | ### About Users @@ -27,6 +30,7 @@ For controls that address threats under these assumptions, see [Mitigations](mit | Assumption | Implication | |------------|-------------| | Cloud providers (Google Cloud, AWS, Fastly) operate securely | Infrastructure compromise outside our control | +| GitHub issues OIDC tokens only to the workflow runs that the claims describe | A compromised GitHub OIDC issuer can publish every package that has a workload identity | | TLS provides confidentiality and integrity in transit | No additional transport encryption | | Cryptographic primitives (RSA, SHA-256, SHA-512) are secure | RSA-PKCS1-SHA512 signatures and SHA-256 checksums depend on this | @@ -55,6 +59,16 @@ For controls that address threats under these assumptions, see [Mitigations](mit | Real-world identity of maintainers | Account verification is email-based only | | Organization membership implies employment | No employment verification | +### Publishing Controls + +| Non-Guarantee | Reason | +|---------------|--------| +| Every release was approved by a person | Staged publishing is off by default for existing packages, and does not hold publishes by a person with OAuth and a 2FA code | +| Staged publishing stops a leaked key | A key with `api:write`, `owners`, `package:NAME`, or `members` can add an owner or member, who then publishes without staging | +| Removing an owner stops their workload identities | Package workload identities stay when an owner is removed without a transfer. A removed owner who can still run a trusted workflow can still publish | +| Removing a workload identity stops fetch tokens at once | repo.hex.pm verifies tokens without hex.pm, so a fetch token stays valid for up to 15 minutes | +| Every release from CI has a verified CI identity | Releases published from CI with an API key have no `oidc_claims` | + ### Availability | Non-Guarantee | Reason | @@ -92,6 +106,7 @@ For controls that address threats under these assumptions, see [Mitigations](mit > - Artifact matches what maintainer published (integrity) > - Registry metadata is authentic (signatures) > - Publishing required authentication +> - A release with `oidc_claims` was published by a GitHub Actions job that matched a workload identity, and the claims are the ones GitHub signed > [!CAUTION] > **What users CANNOT assume:** @@ -106,7 +121,6 @@ Planned features that will change (but not eliminate) these assumptions: | Feature | Impact on Assumptions | |---------|----------------------| -| Trusted Publishing (OIDC) | Provides build provenance; reduces "maintainer environment" assumption | | Malware scanning | Provides some content assurance; still cannot guarantee safety | | Signed attestations | Provides verifiable claims about build process | | WebAuthn/Passkeys | Reduces account compromise risk | diff --git a/security/threat-model/client-flows.md b/security/threat-model/client-flows.md index 92db614..bcb02d7 100644 --- a/security/threat-model/client-flows.md +++ b/security/threat-model/client-flows.md @@ -52,6 +52,8 @@ Command: `mix deps.get` Mix/Hex uses OAuth2 Device Authorization Grant ([RFC 8628](https://datatracker.ietf.org/doc/html/rfc8628)) for interactive authentication. `mix hex.user auth` requests the `api repositories` scopes, which include both read and write permissions; write operations additionally require 2FA to be enabled on the account and an OTP code in the `x-hex-otp` header. API keys can still be used directly, especially for CI environments; API keys cannot use 2FA. See [OAuth2 Device Authorization Grant](#6-oauth2-device-authorization-grant) for details. +In a GitHub Actions job with the `id-token: write` permission, Mix fetches packages from an organization repository with Workload Identity when no organization key or signed-in user is configured. See [Workload Identity](#7-workload-identity). + ### Cache Locations | Cache | Path | Contents | @@ -196,7 +198,7 @@ Command: `rebar3 compile` (with hex plugin) ### Authentication -Rebar3 uses basic authentication to generate API keys. Unlike Mix/Hex and Gleam, it does not support OAuth2 Device Authorization Grant. +Rebar3 uses the OAuth2 Device Authorization Grant through `rebar3 hex user auth`, the same as Mix/Hex and Gleam. The API no longer accepts Basic authentication, so older Rebar3 versions that create keys with a password cannot authenticate. ### Cache Locations @@ -369,11 +371,17 @@ Publishing requires write permissions: | Client | Authentication Method | 2FA Requirement | |--------|----------------------|-----------------| -| Mix/Hex | OAuth token or API key | Required for OAuth tokens | +| Mix/Hex | OAuth token, API key, or Workload Identity | Required for OAuth tokens | | Gleam | OAuth token or API key | Required for OAuth tokens | -| Rebar3 | API key (via basic auth) | Not supported | +| Rebar3 | OAuth token, API key, or Workload Identity | Required for OAuth tokens | + +For OAuth tokens, write operations prompt for a 2FA code which is sent via the `x-hex-otp` header. In GitHub Actions, `mix hex.publish` and `rebar3 hex publish` exchange the job's OIDC token for a workload identity token when no other credential is configured. See [Workload Identity](#7-workload-identity). + +### Staged Publishing -For OAuth tokens, write operations prompt for a 2FA code which is sent via the `x-hex-otp` header. +When a package uses staged publishing, the API holds releases and documentation from an API key, an organization key token, or a workload identity. It answers `201 Created` with a staged release instead of a release, and does not publish yet. A maintainer with 2FA compares the checksums and approves or rejects on the dashboard. Publishes by a person with an OAuth token and a 2FA code are not held. + +`mix hex.publish --wait` and `rebar3 hex publish --wait` open the approval page and poll the staged release URL from the `Location` header until it is approved, rejected, or expired. Mix binds the wait to the checksums that the API reported for the staged release, so a restaged release fails the wait. ### Sequence Diagram @@ -442,8 +450,20 @@ sequenceDiagram Worker->>Worker: Gzip compress Worker->>S3: Upload registry files - API-->>Client: 201 Created - Client-->>Dev: ✓ Package published + alt Staged publishing applies + API->>API: Store staged release, do not publish + API-->>Client: 201 Created (staged release, Location: staged URL) + Client-->>Dev: Approval URL, expiry, checksums + opt --wait + loop Until approved, rejected, or expired + Client->>API: GET {staged URL} + API-->>Client: status + end + end + else Published directly + API-->>Client: 201 Created + Client-->>Dev: ✓ Package published + end Note over Dev: Optional: Publish docs Dev->>Client: mix hex.docs (automatic) @@ -549,7 +569,7 @@ sequenceDiagram ## 6. OAuth2 Device Authorization Grant -Mix/Hex and Gleam use [RFC 8628 OAuth2 Device Authorization Grant](https://datatracker.ietf.org/doc/html/rfc8628) for interactive authentication. This flow is designed for CLI tools that cannot easily handle browser redirects. +Mix/Hex, Rebar3, and Gleam use [RFC 8628 OAuth2 Device Authorization Grant](https://datatracker.ietf.org/doc/html/rfc8628) for interactive authentication. This flow is designed for CLI tools that cannot easily handle browser redirects. ### Supported Clients @@ -557,7 +577,7 @@ Mix/Hex and Gleam use [RFC 8628 OAuth2 Device Authorization Grant](https://datat |--------|--------------|----------| | Mix/Hex | Yes (default) | API keys via `HEX_API_KEY` | | Gleam | Yes (default) | API keys via `HEXPM_API_KEY` | -| Rebar3 | No | Basic auth for API key generation | +| Rebar3 | Yes (default) | API keys via `HEX_API_KEY` | ### OAuth Endpoints @@ -566,6 +586,7 @@ Mix/Hex and Gleam use [RFC 8628 OAuth2 Device Authorization Grant](https://datat | `/api/oauth/device_authorization` | POST | Initiate device flow | | `/api/oauth/token` | POST | Exchange codes for tokens / refresh tokens | | `/api/oauth/revoke` | POST | Revoke tokens | +| `/api/oauth/organization_authorization` | POST | Sign in to organizations that require single sign-on | ### Token Properties @@ -573,7 +594,7 @@ Mix/Hex and Gleam use [RFC 8628 OAuth2 Device Authorization Grant](https://datat |----------|-------| | Access token lifetime | Short-lived (configurable) | | Refresh token lifetime | Long-lived | -| Scopes requested by clients | `mix hex.user auth`: `api repositories` (full API + per-repository scopes). Gleam: `api:write`. | +| Scopes requested by clients | `mix hex.user auth`: `api repositories` (full API + per-repository scopes). `rebar3 hex user auth`: `api:write`. Gleam: `api:write`. | | Write operations | Require 2FA via `x-hex-otp` header | ### Sequence Diagram @@ -680,6 +701,12 @@ sequenceDiagram - Token storage: `~/.hex/hex.config` - Commands: `mix hex.user auth`, `mix hex.user deauth` +#### Rebar3 + +- Client ID: `b9721cf5-be2f-4a65-bfa5-141698b4b9cf` +- Token storage: `~/.config/rebar3/hex.config`, under the `$oauth` key (`REBAR_GLOBAL_CONFIG_DIR` overrides the base directory) +- Commands: `rebar3 hex user auth`, `rebar3 hex user deauth` + #### Gleam - Client ID: `877731e8-cb88-45e1-9b84-9214de7da421` @@ -688,6 +715,64 @@ sequenceDiagram --- +## 7. Workload Identity + +A GitHub Actions job exchanges its OIDC token for a short-lived Hex token instead of using a stored API key. A full package owner, or an organization admin, configures the workload identity on hex.pm with 2FA. It names the GitHub owner, the repositories, the workflow file, and the environment. + +### Token Properties + +| Property | Value | +|----------|-------| +| OIDC audience | Configured in the client, `hexpm` by default. The client checks it against `GET /api/oidc/audience` and stops if they differ | +| OIDC token reuse | Refused. Each OIDC token is exchanged at most once | +| Scope | `package:REPOSITORY/PACKAGE` to publish one package, or `repository:ORGANIZATION` to fetch | +| Lifetime | 15 minutes, no refresh token | +| Write operations | Publish releases and documentation only. No revert, retire, owner, key, member, or setting changes | +| Refused triggers | `pull_request_target`, `workflow_run` | + +### Sequence Diagram + +```mermaid +sequenceDiagram + autonumber + participant Job as GitHub Actions Job + participant GH as GitHub OIDC Issuer + participant API as hex.pm API + participant CDN as repo.hex.pm + + Job->>API: GET /api/oidc/audience + API-->>Job: {"audience": "hexpm"} + alt Reported audience differs from the configured audience + Job->>Job: Stop, do not request an OIDC token + end + Job->>GH: Request OIDC token (configured audience) + GH-->>Job: Signed JWT (repository, workflow, environment, sha, actor) + + Job->>API: POST /api/oauth/token
grant_type=jwt-bearer, assertion=JWT, scope=package:hexpm/PACKAGE + API->>API: Verify signature, audience, expiry, jti not used + API->>API: Refuse pull_request_target and workflow_run + API->>API: Match pinned owner and repository IDs, workflow, environment + alt Match + API-->>Job: access_token (15 minutes) + else No match + API-->>Job: 403 access_denied + end + + Job->>API: POST /api/publish
Authorization: Bearer {access_token} + API->>API: Record OIDC claims on the release + API-->>Job: 201 Created (release, or staged release) + + opt Fetch private packages (scope=repository:ORG) + Job->>CDN: GET /repos/ORG/...
Authorization: Bearer {access_token} + CDN->>CDN: Verify token at the edge + CDN-->>Job: Registry or tarball + end +``` + +repo.hex.pm verifies fetch tokens at the edge without hex.pm. A fetch token stays valid for up to 15 minutes after the workload identity is removed. + +--- + ## Verification Summary All clients perform these verification steps: diff --git a/security/threat-model/mitigations.md b/security/threat-model/mitigations.md index 9b1eae2..45a3208 100644 --- a/security/threat-model/mitigations.md +++ b/security/threat-model/mitigations.md @@ -18,12 +18,14 @@ Addresses: [T1](threats.md#t1-malicious-package-publication), [T4](threats.md#t4 | Email verification | Implemented | Users must verify email addresses for account recovery | | Password minimum length | Implemented | Minimum 8 characters, no complexity rules | | Leaked password detection | Implemented | Checks passwords against HaveIBeenPwned API on login and password change; warns users but allows login | -| Two-factor authentication (TOTP) | Implemented | Optional for login, required for write operations with OAuth | +| Two-factor authentication (TOTP) | Implemented | Optional for login. Required for write operations with OAuth, for adding, changing, or removing workload identities, and for approving staged releases | | Phishing-resistant 2FA (WebAuthn) | Planned | Hardware security keys and passkeys | | Passwordless authentication | Planned | Passkey-based access methods | | OAuth2 Device Authorization Grant | Implemented | Secure CLI authentication flow. See [Client Flows](client-flows.md#6-oauth2-device-authorization-grant) | | Login rate limiting | Implemented | 10 attempts per IP per 15 minutes | -| Mandatory 2FA for maintainers | Planned | Requires rebar3 OAuth migration, then disable basic auth; 2FA already required for OAuth write operations | +| Basic authentication removed | Implemented | The API refuses Basic authentication since 2026-11-01. Mix, Rebar3, and Gleam use the OAuth2 Device Authorization Grant | +| Organization 2FA enforcement | Implemented | An organization can require 2FA for its members | +| Mandatory 2FA for maintainers | Implemented | Every credential that can publish requires 2FA. OAuth write operations need an OTP code. The API and the dashboard refuse keys with `api`, `api:write`, `publish`, `publish:NAME`, or `package:NAME` permissions for an account without 2FA | | Critical package MFA | Partial | Require MFA for maintainers of high-impact packages | | Abandoned domain detection | Planned | Detect and disable account recovery via expired email domains | | Security notifications | Implemented | Alert maintainers about critical account changes via email | @@ -33,14 +35,36 @@ Addresses: [T1](threats.md#t1-malicious-package-publication), [T4](threats.md#t4 | Control | Status | Description | |---------|--------|-------------| -| Scoped API tokens | Implemented | Tokens can be scoped by domain (api, repository, package, docs) and resource (read/write, specific repos/packages) | +| Scoped API tokens | Implemented | Tokens can be scoped by domain (`api`, `package`, `publish`, `owners`, `members`, `administration`, `repository`, `repositories`, `docs`) and resource (read/write, specific repositories or packages). `publish:NAME` lets a CI key publish one package without the right to change owners | | Short-lived OAuth access tokens | Implemented | Access tokens expire quickly, refresh tokens for renewal | | Token revocation | Implemented | Users can revoke tokens at any time | | API key expiry dates | Implemented | Allow setting expiration on API keys | -| Token prefixing | Planned | Distinctive repository identifiers on all tokens | -| Secret scanning integration | Planned | Tokens compatible with third-party secret detection tools with automated revocation | +| Token prefixing | Implemented | New API keys have a `hex_` prefix and a CRC32 checksum. Keys created before this format have no prefix | +| Secret scanning integration | Implemented | Hex.pm is a GitHub Secret Scanning partner. When GitHub reports a leaked key in a public repository, Hex.pm revokes the key and emails its owner | +| Keys cannot manage keys | Implemented | Only a signed-in person can create or revoke keys. A leaked key cannot create keys that outlive it or revoke the owner's other keys | +| Revocation of exchanged tokens | Implemented | Revoking a key also revokes the short-lived tokens that were exchanged from it | | 2FA for write operations | Implemented | OAuth tokens require 2FA for publishing. See [Client Flows](client-flows.md#write-operations-with-2fa) | +### Workload Identity + +Short-lived, scoped credentials for CI jobs in place of stored API keys. See [Client Flows](client-flows.md#7-workload-identity) and [Supply Chain - Provenance](../supply-chain/provenance.md). + +| Control | Status | Description | +|---------|--------|-------------| +| OIDC token exchange | Implemented | GitHub Actions only. A CI job exchanges a GitHub OIDC token for a Hex token with the JWT Bearer Grant | +| Short-lived scoped tokens | Implemented | Tokens expire after 15 minutes. A publish token covers one package and cannot revert, retire, or change owners, keys, members, or settings | +| Single-use OIDC tokens | Implemented | Each OIDC token is accepted once (`jti` replay check). OIDC tokens valid for more than 15 minutes are refused | +| Immutable GitHub IDs | Implemented | The owner and repository IDs are pinned, so a deleted and re-created GitHub account or repository does not inherit a workload identity | +| Environment required for public repositories | Implemented | A workload identity that names a public repository must name a GitHub environment, so GitHub protection rules apply before the job gets a token | +| Privileged trigger refusal | Implemented | Tokens from `pull_request_target` and `workflow_run` events are refused, because a pull request from a fork can trigger them | +| Client audience pinning | Partial | hex_core, which Mix and Rebar3 use, requests OIDC tokens only for a configured audience (`hexpm` by default). It stops when `GET /api/oidc/audience` reports a different value. Hand-written workflows that request a token for the reported audience do not have this protection | +| Configuration requires full ownership and 2FA | Implemented | Full package owners, or organization admins for organization workload identities, configure them with 2FA enabled | +| Configuration change notifications | Implemented | Package owners or organization admins are emailed when a workload identity is added, removed, or changed to trust more | +| Removal on package transfer | Implemented | Transferring a package removes its package workload identities | +| Token revocation on narrowing | Implemented | Removing a repository or changing the workflow or environment revokes the tokens the workload identity issued | +| Exchange rate limits | Implemented | 1,000 exchanges per address per minute. Failed exchanges after verification count toward a limit per GitHub repository | +| Additional CI providers | Planned | GitLab and other OIDC issuers are not supported | + ### Session Security | Control | Status | Description | @@ -62,6 +86,21 @@ Addresses: [T1](threats.md#t1-malicious-package-publication), [T2](threats.md#t2 | Owner levels | Implemented | "full" (can manage owners) vs "maintainer" (can publish only) | | Transfer confirmation | Implemented | Ownership transfers require confirmation | +### Staged Publishing + +Holds releases and documentation from automated credentials until a person approves them. See [Client Flows](client-flows.md#staged-publishing). + +| Control | Status | Description | +|---------|--------|-------------| +| Approval for automated publishes | Implemented | Releases and documentation published with an API key, an organization key token, or a workload identity are stored as staged releases. Publishes by a person with OAuth and a 2FA code are not held | +| Default for new packages | Implemented | New packages require approval by default. Existing packages start with it off | +| Organization requirement | Implemented | An organization can require staged publishing for every package in its private repository | +| Approval requires 2FA | Implemented | A maintainer with 2FA approves or rejects on the dashboard after comparing the package and documentation checksums | +| Expiry | Implemented | Staged releases expire after seven days | +| Revert restriction | Implemented | API keys cannot revert releases or documentation of packages that use staged publishing | +| Disable notification | Implemented | Turning staged publishing off requires 2FA and fresh verification, and emails full owners and owning organization admins | +| Emergency publishing mode | Implemented | During an incident, operators can require approval for every public package publish from an API key, organization key token, or workload identity, whatever the package settings. Keys cannot revert public releases in this mode | + ### Audit Trail | Control | Status | Description | @@ -102,9 +141,9 @@ Addresses: [T3](threats.md#t3-package-tampering) | Control | Status | Description | |---------|--------|-------------| -| Trusted Publishing (OIDC) | Planned | CI provider integration for keyless publishing | +| Workload Identity (OIDC) | Partial | Keyless publishing from GitHub Actions. Other CI providers are not supported. See [Workload Identity](#workload-identity) | | Build attestations (SLSA) | Planned | Cryptographic proof of build origin | -| Source repository linking | Partial | Links exist but not cryptographically verified | +| Source repository linking | Partial | Releases published with a workload identity record the verified OIDC claims (repository, commit, workflow, actor) and expose them as `oidc_claims`. Other source links are maintainer-provided and not verified | See [Supply Chain - Provenance](../supply-chain/provenance.md). @@ -303,13 +342,13 @@ Addresses: [T9](threats.md#t9-unmaintainedabandoned-packages) | Threat | Primary Mitigations | Status | Notes | |--------|---------------------|--------|-------| -| T1: Malicious publication | 2FA, token scoping, audit logs | Implemented | 2FA optional for login | +| T1: Malicious publication | 2FA, token scoping, staged publishing, audit logs | Implemented | 2FA optional for login. Staged publishing is off by default for existing packages | | T2: Typosquatting | Levenshtein check, community reports | Partial | Detection is alert-only | | T3: Package tampering | Signatures, checksums | Implemented | Strong coverage | -| T4: Account takeover | 2FA, OAuth, leaked password check, rate limiting | Implemented | 2FA optional for login | +| T4: Account takeover | 2FA, OAuth, leaked password check, secret scanning, rate limiting | Implemented | 2FA optional for login | | T5: Documentation attacks | Origin separation, CSP, sandboxing | Implemented | Strong coverage | | T6: Registry compromise | Access control, monitoring | Implemented | Strong coverage | | T7: DoS | Rate limiting, CDN | Implemented | Strong coverage | | T8: Vulnerable dependencies | OSV ingestion, advisory CLI reporting, dependency policies, CNA | Partial | Advisory consumption and policy enforcement in Hex (Elixir/Mix); not yet in Rebar3 or Gleam | | T9: Unmaintained packages | Metadata, retirement status | Partial | Succession process informal | -| T10: Build pipeline compromise | (Planned: Trusted Publishing) | Planned | Gap - highest priority | +| T10: Build pipeline compromise | Workload Identity, staged publishing | Partial | GitHub Actions only. No build attestations. A compromised workflow that matches a workload identity can still publish unless staged publishing applies | diff --git a/security/threat-model/overview.md b/security/threat-model/overview.md index 997f88e..6758b75 100644 --- a/security/threat-model/overview.md +++ b/security/threat-model/overview.md @@ -66,7 +66,7 @@ See [Threats](./threats.md) for detailed descriptions. Hex.pm is the distribution point, not the build system. This means: -- **Limited control over T10**: Build happens on maintainer machines +- **Limited control over T10**: Build happens on maintainer machines or in CI. Workload Identity binds CI publishes to a GitHub workflow, and staged publishing adds human approval, but Hex.pm cannot see inside the build - **Strong control over T3**: Registry signing and checksums provide tamper evidence - **Shared responsibility for T1/T4**: Authentication controls, but maintainers control their credentials diff --git a/security/threat-model/threats.md b/security/threat-model/threats.md index 121eae6..a5f98f9 100644 --- a/security/threat-model/threats.md +++ b/security/threat-model/threats.md @@ -16,6 +16,8 @@ An attacker publishes a package containing malicious code designed to harm users | Malicious maintainer | Insider threat from package owner | Supply chain attacks | | Compromised CI/CD | Attack on maintainer's build/publish pipeline | Supply chain attacks | | Social engineering | Convincing maintainer to add malicious contributor | Supply chain attacks | +| Leaked automation credential | Publishing with a stolen API key or CI token without the maintainer's 2FA | Supply chain attacks | +| Staging bypass via owner change | A key with `api:write`, `owners`, `package:NAME`, or `members` adds an owner or member, who then publishes with OAuth and 2FA without staged publishing | Supply chain attacks | ### Real-World Examples @@ -45,7 +47,7 @@ An attacker publishes a package containing malicious code designed to harm users ### Related Controls -See [Mitigations](./mitigations.md#identity--access) for controls. +See [Mitigations](./mitigations.md#identity--access) for controls, and [Staged Publishing](./mitigations.md#staged-publishing) for approval of automated publishes. ## T2: Typosquatting / Dependency Confusion @@ -160,6 +162,7 @@ An attacker gains unauthorized access to a maintainer or administrator account. | Credential reuse | Password from other breaches | Supply chain attacks | | Phishing | Fake login pages, OAuth consent abuse | Supply chain attacks | | Token leakage | API keys in logs, repos, screenshots | Supply chain attacks | +| Key self-propagation | A leaked key creates new keys that outlive its revocation | Supply chain attacks | | Session hijacking | Cookie theft, XSS exploitation | Supply chain attacks | | Email domain expiry | Takeover of expired maintainer email domains | Supply chain attacks | @@ -394,6 +397,11 @@ An attacker compromises the build or CI/CD pipeline of package maintainers, inje | Vector | Description | |--------|-------------| | CI/CD credential theft | Stealing publish tokens from CI systems | +| Over-broad workload identity | A workload identity that trusts many repositories, every workflow, or no environment lets anyone who can push a workflow file to one of them publish | +| Privileged workflow triggers | A `pull_request_target` or `workflow_run` workflow runs fork code with the base repository's OIDC permission | +| OIDC audience confusion | A server at an untrusted API URL reports the audience of another service, such as another registry or a cloud provider. A client that requests an OIDC token for that audience gives the server a token that the other service accepts | +| Stale workload identity | A removed owner or organization member keeps control of a GitHub workflow that a workload identity still trusts | +| GitHub account or repository resurrection | An attacker re-creates a deleted GitHub owner or repository under the same name to inherit a workload identity | | Build system compromise | Modifying build scripts or dependencies | | Source repository attacks | Compromising GitHub/GitLab accounts | | IDE/toolchain attacks | Malicious IDE extensions or build tools | @@ -425,7 +433,9 @@ An attacker compromises the build or CI/CD pipeline of package maintainers, inje ### Related Controls -See [Build Provenance](./mitigations.md#build-provenance) under Supply Chain Integrity and [Supply Chain - Provenance](../supply-chain/provenance.md). +See [Workload Identity](./mitigations.md#workload-identity), [Staged Publishing](./mitigations.md#staged-publishing), [Build Provenance](./mitigations.md#build-provenance) under Supply Chain Integrity, and [Supply Chain - Provenance](../supply-chain/provenance.md). + +Workload Identity removes long-lived publish keys from CI, but it moves trust to the GitHub workflow. Anyone who can run a workflow that matches a workload identity can publish the package. Staged publishing adds a human approval step after the CI job. ## Framework Cross-Reference From c4ee1db2306c6f207587164139398893547cce22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonatan=20M=C3=A4nnchen?= Date: Thu, 5 Nov 2026 11:49:22 +0100 Subject: [PATCH 7/7] Update provenance docs and archive the Basic auth risk Co-Authored-By: Claude Opus 5.5 --- security/sdlc/risk-register.md | 3 +-- security/supply-chain/overview.md | 7 +++--- security/supply-chain/provenance.md | 33 +++++++++++++++++------------ 3 files changed, 25 insertions(+), 18 deletions(-) diff --git a/security/sdlc/risk-register.md b/security/sdlc/risk-register.md index 85691d6..952f56a 100644 --- a/security/sdlc/risk-register.md +++ b/security/sdlc/risk-register.md @@ -6,7 +6,6 @@ This document tracks accepted security risks and their mitigations for Hex regis | ID | Risk | Severity | Status | Threats | Mitigation | Reference | |----|------|----------|--------|---------|------------|-----------| -| R-001 | Basic Authentication maintained for backward compatibility | Medium | Mitigating | [T4](../threat-model/threats.md#t4-account-takeover) | OAuth2 migration planned; rate limiting in place | Security Audit 2026 | | R-002 | Documentation hosted as full websites (HTML/JS) | Low | Accepted | [T5](../threat-model/threats.md#t5-documentation-based-attacks) | Malicious content removed upon report | Security Audit 2026 | | R-003 | User enumeration via API | Low | Accepted | [T4](../threat-model/threats.md#t4-account-takeover) | Users are public for package publication; profile info is user-provided | Security Audit 2026 | | R-004 | No WAF | Low | Accepted | [T6](../threat-model/threats.md#t6-registry-infrastructure-compromise) | SQL injection prevented by Ecto; XSS prevented by CSP; little added value expected | Security Audit 2026 | @@ -40,4 +39,4 @@ This document tracks accepted security risks and their mitigations for Hex regis | ID | Risk | Resolution Date | Resolution | |----|------|-----------------|------------| -| - | - | - | - | +| R-001 | Basic Authentication maintained for backward compatibility | 2026-11-01 | The API refuses Basic authentication. Mix, Rebar3, and Gleam use the OAuth2 Device Authorization Grant | diff --git a/security/supply-chain/overview.md b/security/supply-chain/overview.md index a9e7a82..f05f828 100644 --- a/security/supply-chain/overview.md +++ b/security/supply-chain/overview.md @@ -48,7 +48,8 @@ flowchart LR | Audit logging | All publishing actions are logged | Implemented | | Owner notifications | All package owners are notified by email when a new version is published or when owners are added or removed | Implemented | | 2FA for publishing | OTP required for write operations via OAuth | Implemented | -| Trusted publishing (OIDC) | Short-lived CI credentials | Planned | +| Workload Identity (OIDC) | Short-lived CI credentials from GitHub Actions | Implemented | +| Staged publishing | Human approval with 2FA for publishes from API keys and workload identities | Implemented | | Build provenance (SLSA) | Cryptographic proof of build origin | Planned | ### Distribution Side @@ -74,8 +75,8 @@ flowchart LR | Stage | Threats | Current Mitigations | |-------|---------|---------------------| | Maintainer | Compromised credentials, malicious insider | 2FA, OAuth, audit logs | -| Build | Compromised build environment | None (planned: trusted publishing, SLSA provenance) | -| Publishing | Unauthorized publish, tampering | Authentication, authorization | +| Build | Compromised build environment | Workload Identity binds publishes to a GitHub workflow, staged publishing (planned: SLSA provenance) | +| Publishing | Unauthorized publish, tampering | Authentication, authorization, staged publishing | | Distribution | CDN/mirror tampering, MITM | Signed registry, checksums | | Consumption | Dependency confusion, typosquatting, vulnerable/retired versions | Repository field verification, typosquatting detection, advisory CLI reporting and dependency policies (Hex/Mix) | diff --git a/security/supply-chain/provenance.md b/security/supply-chain/provenance.md index 5dec736..11b1711 100644 --- a/security/supply-chain/provenance.md +++ b/security/supply-chain/provenance.md @@ -18,34 +18,40 @@ Provenance answers: | Attribute | Tracked | Verifiable | Notes | |-----------|---------|------------|-------| | Publishing user | Yes | Via audit log | Account that initiated publish | +| CI identity | Yes, for Workload Identity publishes | Via API (`oidc_claims`) | Verified GitHub repository, commit, workflow, ref, environment, run, and actor | +| Approver | Yes, for staged releases | Via audit log | Person who approved the staged release | | Publish timestamp | Yes | Via API | Stored on the release record and exposed via the HTTP API; not part of the signed registry | | Publishing IP/client | Yes | Via audit log | Internal only | -| Source repository | Yes | Metadata only | Maintainer-provided, not verified | +| Source repository | Yes | Metadata only, or `oidc_claims` | Maintainer-provided and not verified, except the repository in `oidc_claims` | | Build environment | No | No | Planned with SLSA provenance | | Build commands | No | No | Planned with SLSA provenance | -### Limitations +### Workload Identity (OIDC) -- No cryptographic proof of build origin -- Source link is maintainer-provided metadata (not verified) -- Build environment is not attested -- No way to verify package was built from claimed source - -## Planned Improvements - -### Trusted Publishing (OIDC) +Workload Identity, sometimes also known as Trusted Publishing, lets a GitHub Actions job publish without a stored API key. Hex.pm verifies the job's OIDC token, matches it against a workload identity that the package owners configured, and records the verified claims on the release. The release API exposes them as `oidc_claims`. The package page shows them in a Provenance card. | Feature | Description | Status | |---------|-------------|--------| -| GitHub Actions | OIDC-based publishing from GitHub CI | Planned | +| GitHub Actions | OIDC-based publishing from GitHub CI | Implemented | | GitLab CI | OIDC-based publishing from GitLab | Planned | | Other providers | Extensible OIDC provider support | Future | Benefits: - No long-lived secrets needed in CI -- Verifiable link to source repository +- Verified link to the source repository and commit - Repository-bound publishing authority +The claims say which workflow run published the release. They do not prove what the workflow built. The record is in the hex.pm database and the API, and is not part of the signed registry. + +### Limitations + +- No cryptographic proof of build origin that clients can verify offline +- Source link is maintainer-provided metadata (not verified), except for Workload Identity publishes +- Build environment is not attested +- No way to verify package was built from claimed source + +## Planned Improvements + ### SLSA Build Provenance SLSA (Supply-chain Levels for Software Artifacts) provenance provides @@ -82,7 +88,8 @@ All publication events will be recorded in an append-only transparency log: |-------------------|-------------|----------------------| | Manual (API key) | Low | Account only | | OAuth with 2FA | Medium | Account + 2FA | -| Trusted Publishing | High | Account + CI identity + repository | +| API key or Workload Identity with staged publishing | Medium | Credential + approval by a maintainer with 2FA | +| Workload Identity | High | Package owner configuration + CI identity + repository | | SLSA Provenance | Highest | Full build chain verification | ## Consumer Guidance