Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions bin/core/src/api/write/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,9 @@ pub enum WriteRequest {
CreateApiKeyForServiceUser(CreateApiKeyForServiceUser),
DeleteApiKeyForServiceUser(DeleteApiKeyForServiceUser),

// ==== API KEY ====
RotateApiKey(RotateApiKey),

// ==== USER GROUP ====
CreateUserGroup(CreateUserGroup),
RenameUserGroup(RenameUserGroup),
Expand Down
62 changes: 62 additions & 0 deletions bin/core/src/api/write/service_user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,65 @@ impl Resolve<WriteArgs> for DeleteApiKeyForServiceUser {
Ok(DeleteApiKeyForServiceUserResponse {})
}
}

impl Resolve<WriteArgs> for RotateApiKey {
#[instrument(
"RotateApiKey",
skip_all,
fields(
operator = user.id,
key = self.key,
)
)]
async fn resolve(
self,
WriteArgs { user }: &WriteArgs,
) -> mogh_error::Result<RotateApiKeyResponse> {
let db = db_client();

let api_key = db
.api_keys
.find_one(doc! { "key": &self.key })
.await
.context("failed to query db for api key")?
.context("did not find matching api key")?;

if api_key.user_id != user.id {
if !user.admin {
return Err(
anyhow!("Can only rotate your own api keys")
.status_code(StatusCode::FORBIDDEN),
);
}

let owner = find_one_by_id(&db.users, &api_key.user_id)
.await
.context("failed to query db for user")?
.context("no user found with id")?;

let UserConfig::Service { .. } = &owner.config else {
return Err(
anyhow!("Admins can only rotate Service User api keys")
.status_code(StatusCode::FORBIDDEN),
);
};
}

let res = create_api_key(
&KomodoAuthImpl,
api_key.user_id,
CreateApiKey {
name: api_key.name,
expires: api_key.expires as u64,
},
)
.await?;

db.api_keys
.delete_one(doc! { "key": self.key })
.await
.context("Created new api key, but failed to delete the old one. Delete it manually.")?;

Ok(res)
}
}
33 changes: 33 additions & 0 deletions client/core/rs/src/api/write/api_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,36 @@ pub struct DeleteApiKeyForServiceUser {

#[typeshare]
pub type DeleteApiKeyForServiceUserResponse = NoData;

//

#[cfg(feature = "utoipa")]
#[utoipa::path(
post,
path = "/RotateApiKey",
description = "Rotate an api key. Generates a new key / secret pair with the same name and expiry, and deletes the old one. Users can rotate their own api keys. Admins can also rotate service user api keys.",
request_body(content = RotateApiKey),
responses(
(status = 200, description = "The new api key and secret"),
),
)]
pub fn rotate_api_key() {}

/// Rotate an api key. Generates a new key / secret pair
/// with the same name and expiry, and deletes the old one.
/// Users can rotate their own api keys.
/// Admins can also rotate service user api keys.
/// Response: [CreateApiKeyResponse].
#[typeshare]
#[derive(Serialize, Deserialize, Debug, Clone, Resolve)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[empty_traits(KomodoWriteRequest)]
#[response(RotateApiKeyResponse)]
#[error(mogh_error::Error)]
pub struct RotateApiKey {
/// The api key to rotate
pub key: String,
}

#[typeshare]
pub type RotateApiKeyResponse = CreateApiKeyResponse;
1 change: 1 addition & 0 deletions client/core/ts/src/responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,7 @@ export type WriteResponses = {
UpdateServiceUserDescription: Types.UpdateServiceUserDescriptionResponse;
CreateApiKeyForServiceUser: Types.CreateApiKeyForServiceUserResponse;
DeleteApiKeyForServiceUser: Types.DeleteApiKeyForServiceUserResponse;
RotateApiKey: Types.RotateApiKeyResponse;

// ==== USER GROUP ====
CreateUserGroup: Types.UserGroup;
Expand Down
15 changes: 15 additions & 0 deletions client/core/ts/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6724,6 +6724,20 @@ export interface CreateApiKeyForServiceUser {
expires?: I64;
}

/**
* Rotate an api key. Generates a new key / secret pair
* with the same name and expiry, and deletes the old one.
* Users can rotate their own api keys.
* Admins can also rotate service user api keys.
* Response: [CreateApiKeyResponse].
*/
export interface RotateApiKey {
/** The api key to rotate */
key: string;
}

export type RotateApiKeyResponse = CreateApiKeyResponse;

/** Create a build. Response: [Build]. */
export interface CreateBuild {
/** The name given to newly created build. */
Expand Down Expand Up @@ -11107,6 +11121,7 @@ export type WriteRequest =
| { type: "UpdateServiceUserDescription", params: UpdateServiceUserDescription }
| { type: "CreateApiKeyForServiceUser", params: CreateApiKeyForServiceUser }
| { type: "DeleteApiKeyForServiceUser", params: DeleteApiKeyForServiceUser }
| { type: "RotateApiKey", params: RotateApiKey }
| { type: "CreateUserGroup", params: CreateUserGroup }
| { type: "RenameUserGroup", params: RenameUserGroup }
| { type: "DeleteUserGroup", params: DeleteUserGroup }
Expand Down
59 changes: 58 additions & 1 deletion ui/src/components/api-keys/section.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import NewApiKey from "./new";
import ApiKeysTable from "./table";
import { useInvalidate, useRead, useWrite } from "@/lib/hooks";
import { notifications } from "@mantine/notifications";
import { Box } from "@mantine/core";
import { Box, Button, Group, Modal, Stack, Text } from "@mantine/core";
import { CopyText } from "mogh_ui";
import { Types } from "komodo_client";
import { useState } from "react";

export interface ApiKeysSectionProps extends SectionProps {
/** For service user api keys */
Expand Down Expand Up @@ -42,6 +45,16 @@ export default function ApiKeysSection({
},
},
);
const [rotated, setRotated] = useState<Types.RotateApiKeyResponse>();
const { mutate: rotate, isPending: rotatePending } = useWrite(
"RotateApiKey",
{
onSuccess: (res) => {
inv([userId ? "ListApiKeysForServiceUser" : "ListApiKeys"]);
setRotated(res);
},
},
);
return (
<Section
isPending={isPending}
Expand All @@ -60,12 +73,56 @@ export default function ApiKeysSection({
<ApiKeysTable
noBorder
keys={keys}
onRotate={(key) => rotate({ key })}
rotatePending={rotatePending}
onDelete={(key) =>
userId ? serviceDelete({ key }) : regularDelete({ key })
}
deletePending={userId ? servicePending : regularPending}
/>
)}

<Modal
opened={!!rotated}
onClose={() => setRotated(undefined)}
title={<Text size="lg">API Key Rotated</Text>}
>
{rotated && (
<Stack>
<Text>
Copy the new API key and secret.{" "}
<b>The secret will not be shown again.</b>
</Text>

<Group justify="space-between" wrap="nowrap">
<Text>Key</Text>
<CopyText
content={rotated.key}
label="API key"
w={{ base: 200, lg: 250 }}
/>
</Group>

<Group justify="space-between" wrap="nowrap">
<Text>Secret</Text>
<CopyText
content={rotated.secret}
label="API secret"
w={{ base: 200, lg: 250 }}
/>
</Group>

<Group justify="end">
<Button
leftSection={<ICONS.Clear />}
onClick={() => setRotated(undefined)}
>
Close
</Button>
</Group>
</Stack>
)}
</Modal>
</Section>
);
}
16 changes: 16 additions & 0 deletions ui/src/components/api-keys/table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,17 @@ const ONE_DAY_MS = 1000 * 60 * 60 * 24;

export interface ApiKeysTableProps {
keys: Types.ApiKey[];
onRotate: (key: string) => void;
rotatePending: boolean;
onDelete: (key: string) => void;
deletePending: boolean;
noBorder?: boolean;
}

export default function ApiKeysTable({
keys,
onRotate,
rotatePending,
onDelete,
deletePending,
noBorder,
Expand Down Expand Up @@ -60,6 +64,18 @@ export default function ApiKeysTable({
);
},
},
{
header: "Rotate",
cell: ({ row }) => (
<ConfirmButton
icon={<ICONS.RotateKey size="1rem" />}
onClick={() => onRotate(row.original.key)}
loading={rotatePending}
>
Rotate
</ConfirmButton>
),
},
{
header: "Delete",
cell: ({ row }) => (
Expand Down