Add API tokens for scripts and CI (0.57.0)
A session token is the wrong credential for automation. It expires in an hour, it is minted by typing a password, and revoking it signs every one of that person's devices out. So automation gets its own credential, revocable on its own, and showing up in the audit log as itself. Three decisions worth recording, because each one is a place this could have been built wrong. **Only a hash is stored.** This is the opposite call from registry passwords one release ago, and for a concrete reason: a registry password has to be handed back to the registry, so it must be recoverable and is encrypted. A token is only ever compared against, so it does not need to be — and not keeping it is the difference between leaking the database and leaking everything the database protects. It is shown once and cannot be recovered; a readable prefix is kept so rows are still identifiable in the UI and the audit log. The hash is SHA-256, deliberately not bcrypt: bcrypt is slow to make guessing low-entropy human passwords expensive, and a token is 256 bits of secrets output, so the cost would buy nothing and would land on every single API request. **The scope is not folded into the User object.** get_current_user returns a session-attached row; downgrading its role in place to represent a read-only token would be written back to the database the next time anything committed that user — logout-everywhere does exactly that. So the token row is stashed on request.state and require_admin consults it, leaving the User untouched. The same lookup caps a token at its owner's authority rather than trusting the scope alone, so a demoted admin's token drops to read-only with them and a disabled account's tokens stop working. **A token cannot make itself permanent.** Creating tokens and creating users now require a signed-in session, via a require_session dependency that rejects token-authenticated requests. Without it, a leaked CI credential could mint a second one and survive its own revocation — the failure mode where revoking the leak does nothing. This is the one behaviour change for existing installs: scripted user creation now needs a login. The WebSocket routes still take JWTs only. They carry logs, the terminal and the deploy console, which a CI job has no use for, and leaving them alone keeps the token surface to the REST API. 19 tests, covering what is stored, that a read token really is read-only while its owner is an admin, that demoting and disabling the owner both take effect, expiry, tampering, the throttle on last-used writes, and that a token can neither mint another nor create a user. Verified end to end against a running app: two tokens, both scopes, revocation, and no plaintext anywhere in the database or the list response. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "stackpilot-frontend",
|
||||
"private": true,
|
||||
"version": "0.56.0",
|
||||
"version": "0.57.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import api from "./client";
|
||||
|
||||
const base = "/api/auth/tokens";
|
||||
|
||||
export interface ApiToken {
|
||||
id: number;
|
||||
name: string;
|
||||
/** The readable front of the token — enough to identify it, not to use it. */
|
||||
prefix: string;
|
||||
scope: "read" | "admin";
|
||||
username: string;
|
||||
expires_at: string | null;
|
||||
last_used_at: string | null;
|
||||
created_at: string;
|
||||
expired: boolean;
|
||||
}
|
||||
|
||||
/** The create response: the only time the token itself is ever returned. */
|
||||
export interface ApiTokenCreated extends ApiToken {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export const tokensApi = {
|
||||
list: () => api.get<ApiToken[]>(base).then((r) => r.data),
|
||||
create: (body: { name: string; scope: "read" | "admin"; expires_in_days?: number }) =>
|
||||
api.post<ApiTokenCreated>(base, body).then((r) => r.data),
|
||||
revoke: (id: number) => api.delete(`${base}/${id}`).then((r) => r.data),
|
||||
};
|
||||
@@ -14,6 +14,9 @@ import {
|
||||
CalendarClock,
|
||||
Play,
|
||||
KeyRound,
|
||||
Terminal,
|
||||
Copy,
|
||||
Check,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Badge, Button, Card, Input, Spinner } from "@/components/ui";
|
||||
@@ -29,6 +32,7 @@ import {
|
||||
type RegistryCredentials,
|
||||
type RegistryInput,
|
||||
} from "@/api/registries";
|
||||
import { tokensApi, type ApiToken, type ApiTokenCreated } from "@/api/tokens";
|
||||
import { schedulesApi, type BackupSchedule } from "@/api/schedules";
|
||||
import { stacksApi } from "@/api/stacks";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
@@ -58,6 +62,7 @@ export function Settings() {
|
||||
<DestinationsSection />
|
||||
<SchedulesSection />
|
||||
<NotificationsSection />
|
||||
<ApiTokensSection />
|
||||
<UsersSection />
|
||||
</div>
|
||||
);
|
||||
@@ -989,6 +994,218 @@ function WebhookForm({
|
||||
/* Users */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* API tokens */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
function ApiTokensSection() {
|
||||
const qc = useQueryClient();
|
||||
const { data, isLoading } = useQuery({ queryKey: ["api-tokens"], queryFn: tokensApi.list });
|
||||
const [adding, setAdding] = useState(false);
|
||||
/** Held until dismissed: this is the only time the token is ever shown. */
|
||||
const [created, setCreated] = useState<ApiTokenCreated | null>(null);
|
||||
const invalidate = () => qc.invalidateQueries({ queryKey: ["api-tokens"] });
|
||||
|
||||
return (
|
||||
<section>
|
||||
<SectionTitle icon={<Terminal className="h-4 w-4" />}>API tokens</SectionTitle>
|
||||
<div className="space-y-3">
|
||||
{created && <NewTokenCard created={created} onDismiss={() => setCreated(null)} />}
|
||||
{isLoading ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
data?.map((t) => <TokenRow key={t.id} token={t} onChange={invalidate} />)
|
||||
)}
|
||||
{data?.length === 0 && !adding && !created && (
|
||||
<Card>
|
||||
<p className="text-sm text-slate-500">
|
||||
No API tokens. Create one to drive StackPilot from a script or CI
|
||||
job without handing over a password — each token can be revoked on
|
||||
its own, and a read-only one cannot change anything.
|
||||
</p>
|
||||
</Card>
|
||||
)}
|
||||
{adding ? (
|
||||
<TokenForm
|
||||
onDone={(token) => {
|
||||
setAdding(false);
|
||||
setCreated(token);
|
||||
invalidate();
|
||||
}}
|
||||
onCancel={() => setAdding(false)}
|
||||
/>
|
||||
) : (
|
||||
<Button variant="outline" onClick={() => setAdding(true)}>
|
||||
<Plus className="h-4 w-4" /> Create token
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function NewTokenCard({
|
||||
created,
|
||||
onDismiss,
|
||||
}: {
|
||||
created: ApiTokenCreated;
|
||||
onDismiss: () => void;
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(created.token);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch {
|
||||
// Clipboard access can be refused (no HTTPS, denied permission); the
|
||||
// token is on screen to select by hand either way.
|
||||
toast.error("Could not copy — select the token and copy it manually");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="space-y-3 border-amber-400/60 bg-amber-50/60 dark:bg-amber-500/5">
|
||||
<div>
|
||||
<p className="font-medium">Copy “{created.name}” now</p>
|
||||
<p className="text-sm text-slate-500">
|
||||
This is the only time the token is shown. It is stored hashed, so it
|
||||
cannot be recovered — if you lose it, revoke it and create another.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<code className="min-w-0 flex-1 break-all rounded-lg bg-slate-900 px-3 py-2 font-mono text-xs text-slate-100">
|
||||
{created.token}
|
||||
</code>
|
||||
<Button variant="outline" onClick={copy}>
|
||||
{copied ? <Check className="h-4 w-4 text-green-500" /> : <Copy className="h-4 w-4" />}
|
||||
{copied ? "Copied" : "Copy"}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<Button variant="ghost" onClick={onDismiss}>
|
||||
I have saved it
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function TokenRow({ token, onChange }: { token: ApiToken; onChange: () => void }) {
|
||||
const revoke = useMutation({
|
||||
mutationFn: () => tokensApi.revoke(token.id),
|
||||
onSuccess: () => {
|
||||
toast.success("Token revoked");
|
||||
onChange();
|
||||
},
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-medium">{token.name}</span>
|
||||
<Badge>{token.scope === "admin" ? "full access" : "read-only"}</Badge>
|
||||
{token.expired && <Badge status="error">expired</Badge>}
|
||||
</div>
|
||||
<p className="break-all font-mono text-xs text-slate-500">
|
||||
{token.prefix}… · {token.username}
|
||||
</p>
|
||||
<p className="text-xs text-slate-400">
|
||||
{token.last_used_at
|
||||
? `last used ${relativeTime(token.last_used_at)}`
|
||||
: "never used"}
|
||||
{token.expires_at && ` · expires ${relativeTime(token.expires_at)}`}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="ghost" onClick={() => revoke.mutate()} loading={revoke.isPending}>
|
||||
<Trash2 className="h-4 w-4 text-red-500" />
|
||||
</Button>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function TokenForm({
|
||||
onDone,
|
||||
onCancel,
|
||||
}: {
|
||||
onDone: (token: ApiTokenCreated) => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const [name, setName] = useState("");
|
||||
const [scope, setScope] = useState<"read" | "admin">("read");
|
||||
const [expiry, setExpiry] = useState("");
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: () =>
|
||||
tokensApi.create({
|
||||
name: name.trim(),
|
||||
scope,
|
||||
expires_in_days: expiry ? Number(expiry) : undefined,
|
||||
}),
|
||||
onSuccess: onDone,
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className="space-y-3">
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<label className="space-y-1">
|
||||
<span className="sp-label">Name</span>
|
||||
<Input
|
||||
placeholder="CI deploy"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="space-y-1">
|
||||
<span className="sp-label">Access</span>
|
||||
<select
|
||||
value={scope}
|
||||
onChange={(e) => setScope(e.target.value as "read" | "admin")}
|
||||
className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800"
|
||||
>
|
||||
<option value="read">Read-only</option>
|
||||
<option value="admin">Full access</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="space-y-1">
|
||||
<span className="sp-label">Expires in (days)</span>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
placeholder="Never"
|
||||
value={expiry}
|
||||
onChange={(e) => setExpiry(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<p className="text-xs text-slate-500">
|
||||
The token acts as you. It can never do more than your account can, and
|
||||
it cannot create tokens or user accounts — those need a signed-in
|
||||
session, so a leaked token cannot make itself permanent.
|
||||
</p>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="ghost" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => save.mutate()}
|
||||
loading={save.isPending}
|
||||
disabled={!name.trim()}
|
||||
>
|
||||
Create token
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Users */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
function UsersSection() {
|
||||
const qc = useQueryClient();
|
||||
const me = useAuthStore((s) => s.user);
|
||||
|
||||
Reference in New Issue
Block a user