feat: expose external auth token expiry in agent API and CLI (#26883)

Previously, \`ExternalAuthResponse\` contained no expiry information, so
workspace agents and git credential helpers had no way to know when a
cached token would stop being valid. Every git operation had to call
back to coderd via \`GIT_ASKPASS\` to get a fresh token, adding 1-2
seconds of latency.

This PR surfaces \`OAuthExpiry\` from the database as \`ExpiresAt\` in
\`ExternalAuthResponse\`, allowing agents to cache tokens with correct
eviction timing (compatible with \`git-credential-cache --timeout\` and
\`password_expiry_utc\` introduced in git 2.34).

\`ExpiresAt\` is normalized to UTC before JSON encoding to avoid
sub-minute precision loss that occurs when the PostgreSQL driver applies
historical Local Mean Time (LMT) timezone offsets to year-1 AD
timestamps.

The \`coder external-auth access-token\` CLI command gains \`--output
json\` to print the full response including \`ExpiresAt\`, enabling
scripts to consume the expiry without parsing heuristics.

Closes https://github.com/coder/coder/issues/26036

## Manual Test

<details>
<summary>Setup</summary>

1. Create a GitHub OAuth app at https://github.com/settings/developers
with:
   - Homepage URL: `http://127.0.0.1:3000`
- Authorization callback URL:
`http://127.0.0.1:3000/external-auth/github/callback`

2. Start the dev server with the GitHub provider configured:
   ```sh
CODER_EXTERNAL_AUTH_0_ID=github CODER_EXTERNAL_AUTH_0_TYPE=github
CODER_EXTERNAL_AUTH_0_CLIENT_ID=<client-id>
CODER_EXTERNAL_AUTH_0_CLIENT_SECRET=<client-secret> ./scripts/develop.sh
   ```

3. Log in at `http://127.0.0.1:3000` (use `127.0.0.1`, not `localhost`,
so the OAuth state cookie domain matches the callback URL).

4. Go to Account > External Authentication and click **Connect** next to
GitHub. Complete the OAuth flow.

5. Create a workspace and SSH into it:
   ```sh
   coder create test-workspace
   coder ssh test-workspace
   ```

</details>

<details>
<summary>Flow 1: Token is valid — JSON output includes
<code>expires_at</code></summary>

Inside the workspace, run:

```sh
coder external-auth access-token github --output json
echo "Exit code: $?"
```

Expected output (GitHub tokens have no expiry, so \`expires_at\` is the
zero value):

```json
{
  "access_token": "<redacted>",
  "token_extra": null,
  "url": "",
  "type": "github",
  "expires_at": "0001-01-01T00:00:00Z",
  "username": "<redacted>",
  "password": ""
}
```

```
Exit code: 0
```

</details>

<details>
<summary>Flow 2: Token missing — JSON output includes auth URL, exit
code 1</summary>

Disconnect GitHub in the Coder UI (Account > External Authentication >
Disconnect), then inside the workspace run:

```sh
coder external-auth access-token github --output json
echo "Exit code: $?"
```

Expected output:

```json
{
  "access_token": "",
  "token_extra": null,
  "url": "http://127.0.0.1:3000/external-auth/github",
  "type": "",
  "expires_at": "0001-01-01T00:00:00Z",
  "username": "",
  "password": ""
}
```

```
Exit code: 1
```

</details>
This commit is contained in:
Bobby Ho
2026-07-07 12:38:37 -07:00
committed by GitHub
parent b3766d62be
commit b169f4d8cb
12 changed files with 359 additions and 30 deletions
+43 -18
View File
@@ -26,7 +26,10 @@ func externalAuth() *serpent.Command {
}
func externalAuthAccessToken() *serpent.Command {
var extra string
var (
extra string
outputFormat string
)
agentAuth := &AgentAuth{}
cmd := &serpent.Command{
Use: "access-token <provider>",
@@ -51,16 +54,29 @@ fi
Description: "Obtain an extra property of an access token for additional metadata.",
Command: "coder external-auth access-token slack --extra \"authed_user.id\"",
},
Example{
Description: "Print the full token response as JSON.",
Command: "coder external-auth access-token github --output json",
},
),
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
),
Options: serpent.OptionSet{{
Name: "Extra",
Flag: "extra",
Description: "Extract a field from the \"extra\" properties of the OAuth token.",
Value: serpent.StringOf(&extra),
}},
Options: serpent.OptionSet{
{
Name: "Extra",
Flag: "extra",
Description: "Extract a field from the \"extra\" properties of the OAuth token.",
Value: serpent.StringOf(&extra),
},
{
Name: "Output",
Flag: "output",
Description: "Output format. Available formats: text, json.",
Value: serpent.EnumOf(&outputFormat, "text", "json"),
Default: "text",
},
},
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
@@ -79,14 +95,21 @@ fi
if err != nil {
return xerrors.Errorf("get external auth token: %w", err)
}
if extAuth.URL != "" {
_, err = inv.Stdout.Write([]byte(extAuth.URL))
switch {
case outputFormat == "json":
data, err := json.MarshalIndent(extAuth, "", " ")
if err != nil {
return xerrors.Errorf("marshal external auth response: %w", err)
}
if _, err := inv.Stdout.Write(data); err != nil {
return err
}
return cliui.ErrCanceled
}
if extra != "" {
case extAuth.URL != "":
if _, err := inv.Stdout.Write([]byte(extAuth.URL)); err != nil {
return err
}
case extra != "":
if extAuth.TokenExtra == nil {
return xerrors.Errorf("no extra properties found for token")
}
@@ -95,15 +118,17 @@ fi
return xerrors.Errorf("marshal extra properties: %w", err)
}
result := gjson.GetBytes(data, extra)
_, err = inv.Stdout.Write([]byte(result.String()))
if err != nil {
if _, err := inv.Stdout.Write([]byte(result.String())); err != nil {
return err
}
default:
if _, err := inv.Stdout.Write([]byte(extAuth.AccessToken)); err != nil {
return err
}
return nil
}
_, err = inv.Stdout.Write([]byte(extAuth.AccessToken))
if err != nil {
return err
if extAuth.URL != "" {
return cliui.ErrCanceled
}
return nil
},
+50 -1
View File
@@ -1,10 +1,15 @@
package cli_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/cli/clitest"
"github.com/coder/coder/v2/cli/cliui"
@@ -66,7 +71,7 @@ func TestExternalAuth(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
httpapi.Write(context.Background(), w, http.StatusOK, agentsdk.ExternalAuthResponse{
AccessToken: "bananas",
TokenExtra: map[string]interface{}{
TokenExtra: map[string]any{
"hey": "there",
},
})
@@ -78,4 +83,48 @@ func TestExternalAuth(t *testing.T) {
clitest.Start(t, inv)
stdout.ExpectMatch(ctx, "there")
})
t.Run("JSONOutput", func(t *testing.T) {
t.Parallel()
expiry := time.Now().Add(8 * time.Hour).UTC().Truncate(time.Second)
tests := []struct {
name string
resp agentsdk.ExternalAuthResponse
wantErr error
}{
{
name: "WithExpiry",
resp: agentsdk.ExternalAuthResponse{AccessToken: "bananas", ExpiresAt: expiry},
},
{
name: "WithURL",
resp: agentsdk.ExternalAuthResponse{URL: "https://github.com/login"},
wantErr: cliui.ErrCanceled,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
httpapi.Write(context.Background(), w, http.StatusOK, tt.resp)
}))
t.Cleanup(srv.Close)
inv, _ := clitest.New(t, "--agent-url", srv.URL, "--agent-token", "foo", "external-auth", "access-token", "github", "--output", "json")
buf := new(bytes.Buffer)
inv.Stdout = buf
waiter := clitest.StartWithWaiter(t, inv)
if tt.wantErr != nil {
waiter.RequireIs(tt.wantErr)
} else {
waiter.RequireSuccess()
}
var resp agentsdk.ExternalAuthResponse
require.NoError(t, json.Unmarshal(buf.Bytes(), &resp))
require.Equal(t, tt.resp.AccessToken, resp.AccessToken)
require.Equal(t, tt.resp.URL, resp.URL)
require.Equal(t, tt.resp.ExpiresAt.UTC(), resp.ExpiresAt.UTC())
})
}
})
}
@@ -23,6 +23,10 @@ USAGE:
- Obtain an extra property of an access token for additional metadata.:
$ coder external-auth access-token slack --extra "authed_user.id"
- Print the full token response as JSON.:
$ coder external-auth access-token github --output json
OPTIONS:
--auth string, $CODER_AGENT_AUTH (default: token)
@@ -44,5 +48,8 @@ OPTIONS:
--extra string
Extract a field from the "extra" properties of the OAuth token.
--output text|json (default: text)
Output format. Available formats: text, json.
———
Run `coder --help` for a list of global options.