Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
132 changes: 132 additions & 0 deletions packages/api/src/routes/clouds.tags.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import {describe, expect, test} from 'bun:test'
import {Hono} from 'hono'
import {awsStorageSchema} from '../cloud-spi/storageSchema'
import type {CloudProvider, CloudResource, CloudServiceAdapter, CreateResourceInput} from '../cloud-spi/types'
import {CloudAdapterRegistry} from '../registry/CloudAdapterRegistry'
import {CloudProxyService} from '../service/CloudProxyService'
import type {RuntimeProbe} from '../service/runtimeProbe'
import {createCloudRoutes} from './clouds'

function mockAdapter(overrides: Partial<CloudServiceAdapter> = {}): CloudServiceAdapter {
return {
cloud: 'aws',
service: 'storage',
schema: awsStorageSchema,
list: async () => [],
get: async () => null,
create: async (_input: CreateResourceInput): Promise<CloudResource> => ({
id: 'created',
name: 'created',
cloud: 'aws',
service: 'storage',
type: 'bucket',
region: null,
createdAt: null,
metadata: {},
}),
delete: async () => {},
...overrides,
}
}

/**
* Runtime probes make real HTTP calls to the emulator endpoints, so the tests inject
* stubs, the same way the other route tests do.
*/
function appWithRoutes(adapters: CloudServiceAdapter[]) {
const app = new Hono()
const registry = new CloudAdapterRegistry(adapters)
const reachable: RuntimeProbe = async () => {}
const probes: Record<CloudProvider, RuntimeProbe> = {
aws: reachable,
azure: reachable,
gcp: reachable,
oci: reachable,
}
app.route('/api/clouds', createCloudRoutes(new CloudProxyService(registry, probes)))
return app
}

describe('the tags route', () => {
test('sends the tags to the adapter, with a null value for a removed one', async () => {
const seen: Array<[string, Record<string, string | null>]> = []
const app = appWithRoutes([
mockAdapter({
updateTags: async (id: string, tags: Record<string, string | null>) => {
seen.push([id, tags])
},
}),
])

const res = await app.request('/api/clouds/aws/services/storage/resources/bucket-1/tags', {
method: 'PATCH',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({env: 'prod', owner: null}),
})

expect(res.status).toBe(200)
expect(await res.json()).toEqual({ok: true})
expect(seen).toEqual([['bucket-1', {env: 'prod', owner: null}]])
})

test('refuses a service whose adapter cannot edit tags', async () => {
const app = appWithRoutes([mockAdapter()])

const res = await app.request('/api/clouds/aws/services/storage/resources/bucket-1/tags', {
method: 'PATCH',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({env: 'prod'}),
})

expect(res.status).toBe(501)
expect((await res.json()).code).toBe('operation_not_supported')
})

test('refuses a body that is not an object of tag changes', async () => {
const app = appWithRoutes([mockAdapter({updateTags: async () => {}})])

for (const body of [['env'], 'env', 42, {env: 42}]) {
const res = await app.request('/api/clouds/aws/services/storage/resources/bucket-1/tags', {
method: 'PATCH',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(body),
})

expect(res.status).toBe(400)
}
})

test('a tag named __proto__ is a tag of its own', async () => {
const seen: Array<Record<string, string | null>> = []
const app = appWithRoutes([
mockAdapter({
updateTags: async (_id: string, tags: Record<string, string | null>) => {
seen.push(tags)
},
}),
])

const res = await app.request('/api/clouds/aws/services/storage/resources/bucket-1/tags', {
method: 'PATCH',
headers: {'Content-Type': 'application/json'},
// An own property: a literal would set the prototype instead.
body: JSON.stringify(Object.fromEntries([['__proto__', 'value']])),
})

expect(res.status).toBe(200)
expect(Object.prototype.hasOwnProperty.call(seen[0], '__proto__')).toBe(true)
expect(seen[0]['__proto__']).toBe('value')
})

test('refuses a service that is not one of them', async () => {
const app = appWithRoutes([mockAdapter()])

const res = await app.request('/api/clouds/aws/services/nothing/resources/bucket-1/tags', {
method: 'PATCH',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({env: 'prod'}),
})

expect(res.status).toBe(404)
})
})
38 changes: 38 additions & 0 deletions packages/api/src/routes/clouds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1136,6 +1136,18 @@ export function createCloudRoutes(
})
})

app.patch('/:cloud/services/:service/resources/:id/tags', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
const serviceType = c.req.param('service') as CloudServiceType
if (!isCloudProvider(cloud) || !isServiceType(serviceType)) throw new NotFoundError('Unknown cloud or service')

return withRuntime(c, async () => {
const tags = tagChanges(await jsonBody<Record<string, unknown>>(c))
await svc(c).updateTags(cloud, serviceType, c.req.param('id'), tags)
return c.json({ok: true})
})
})

app.delete('/:cloud/services/:service/resources/:id', async (c) => {
const cloud = c.req.param('cloud') as CloudProvider
const serviceType = c.req.param('service') as CloudServiceType
Expand Down Expand Up @@ -1206,6 +1218,32 @@ function parseStreamReadQuery(query: Record<string, string>): ReadStreamMessages
return input
}

/**
* The tag changes a request carries.
*
* <p>A key with a value is one that is set, and a key with a null is one that is
* removed. The body is checked, because the generic a request is cast to is only a
* compile-time claim: a body that is an array, or one whose values are not
* strings, is a fault of the caller and is refused here rather than reaching the
* cloud.
*
* <p>The changes are built through a map, so a tag named `__proto__` is an own
* property of the result and not the prototype of it.
*/
function tagChanges(body: Record<string, unknown>): Record<string, string | null> {
const changes = new Map<string, string | null>();
for (const [key, value] of Object.entries(body)) {
if (value === null) {
changes.set(key, null);
} else if (typeof value === 'string') {
changes.set(key, value);
} else {
throw new ValidationError(`the tag ${key} must be a string or null`);
}
}
return Object.fromEntries(changes);
}

async function jsonBody<T>(c: Context): Promise<T> {
try {
const body = await c.req.json<unknown>()
Expand Down
12 changes: 12 additions & 0 deletions packages/api/src/service/CloudProxyService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,18 @@ export class CloudProxyService {
await this.requireAdapter(cloud, service).delete(id)
}

/**
* The tags of a resource, changed.
*
* <p>A key with a null value is one whose tag is removed, which is the shape the
* adapter's own `updateTags` takes.
*/
async updateTags(cloud: CloudProvider, service: CloudServiceType, id: string, tags: Record<string, string | null>): Promise<void> {
const adapter = this.requireAdapter(cloud, service)
if (!adapter.updateTags) throw new NotSupportedError(`Tag editing is not supported for ${cloud}/${service}`)
await adapter.updateTags(id, tags)
}

async encryptKms(cloud: CloudProvider, keyId: string, input: KmsEncryptInput): Promise<KmsEncryptResult> {
const adapter = this.requireAdapter(cloud, 'kms')
if (!adapter.encrypt) throw new NotSupportedError(`${cloud}/kms encrypt is not supported`)
Expand Down
9 changes: 9 additions & 0 deletions packages/frontend/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const apiEndpointKeys = {
get: "clouds.services.resources.get",
create: "clouds.services.resources.create",
update: "clouds.services.resources.update",
tags: "clouds.services.resources.tags",
delete: "clouds.services.resources.delete",
invoke: "clouds.services.resources.invoke",
encrypt: "clouds.services.resources.encrypt",
Expand Down Expand Up @@ -507,6 +508,14 @@ export const endpointRegistry: EndpointRegistry = new Map([
telemetry: { service: "cloud-proxy" },
},
],
[
apiEndpointKeys.clouds.resources.tags,
{
path: "/clouds/:cloud/services/:service/resources/:id/tags",
method: "PATCH",
telemetry: { service: "cloud-proxy" },
},
],
[
apiEndpointKeys.clouds.resources.delete,
{
Expand Down
19 changes: 19 additions & 0 deletions packages/frontend/src/api/cloudProxyClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,25 @@ export async function updateCloudResource(
return res.data;
}

/**
* The tags of a resource, changed.
*
* A key with a null value is one whose tag is removed.
*/
export async function updateCloudResourceTags(
cloud: CloudProvider,
service: CloudServiceType,
id: string,
tags: Record<string, string | null>,
signal?: AbortSignal,
): Promise<void> {
await apiClient.call<void, Record<string, string | null>>(
apiEndpointKeys.clouds.resources.tags,
requestOptions(cloud, service, { signal, body: tags }),
{ cloud, service, id },
);
}

export async function deleteCloudResource(
cloud: CloudProvider,
service: CloudServiceType,
Expand Down
1 change: 1 addition & 0 deletions packages/frontend/src/components/DynamicResourceView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1037,6 +1037,7 @@ export function DynamicResourceView({
cloud={cloud}
runtimeReachable={canUseRuntime}
serviceName={schema.displayName}
canEditTags={capabilityEnabled(capabilityFor(resourceCapabilities, "updateTags"))}
/>
)}
</div>
Expand Down
27 changes: 15 additions & 12 deletions packages/frontend/src/components/ResourceInspector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import type { CloudProvider } from "@/types/cloud";
import type { CloudResource, StorageObject } from "@/types/resource";
import { formatBytes } from "@/lib/format";
import { InspectorTabs, type InspectorTab } from "@/components/InspectorTabs";
import { ResourceTagsEditor } from "@/components/ResourceTagsEditor";
import { resourceTags } from "@/lib/resourceTags";
import { lazyPanel } from "@/lib/lazyPanel";

const LogsExplorerPanel = lazyPanel(() => import("@/components/LogsExplorerPanel").then((m) => m.LogsExplorerPanel));
Expand All @@ -20,6 +22,8 @@ interface ResourceInspectorProps {
cloud?: CloudProvider;
runtimeReachable?: boolean;
serviceName?: string;
/** Whether the service's schema declares that its tags can be edited. */
canEditTags?: boolean;
}

export type { InspectorTab };
Expand All @@ -30,6 +34,7 @@ export function ResourceInspector({
cloud,
runtimeReachable,
serviceName,
canEditTags,
}: ResourceInspectorProps) {
const [activeTab, setActiveTab] = useState<InspectorTab>('plain');
const [copiedJson, setCopiedJson] = useState(false);
Expand Down Expand Up @@ -178,7 +183,7 @@ export function ResourceInspector({
return <EmailInspector key={resource.id} resource={resource} />
}

const tags = getTags(resource.metadata.tags);
const tags = resourceTags(resource.metadata);
const tagsUnavailable = getBooleanMetadata(resource.metadata.tagsUnavailable) ?? false;
const versioning = getStringMetadata(resource.metadata.versioning);
const versioningEnabled = getBooleanMetadata(
Expand Down Expand Up @@ -335,6 +340,15 @@ export function ResourceInspector({
))}
</div>
)}
{canEditTags && resource && (
<ResourceTagsEditor
key={resource.id}
resource={resource}
cloud={resourceCloud ?? resource.cloud}
tags={tags}
runtimeReachable={runtimeReachable ?? false}
/>
)}
</section>
{isDatabase && (
<DatabaseConnectionsSection metadata={resource.metadata} />
Expand Down Expand Up @@ -754,17 +768,6 @@ function getRecordMetadata(value: unknown): Record<string, unknown> | null {
: null;
}

function getTags(value: unknown): Array<{ key: string; value: string }> {
if (!Array.isArray(value)) return [];
return value.flatMap((item) => {
if (!item || typeof item !== "object") return [];
const tag = item as Record<string, unknown>;
return typeof tag.key === "string" && typeof tag.value === "string"
? [{ key: tag.key, value: tag.value }]
: [];
});
}

function getSecurityGroups(
value: unknown,
): Array<{ id: string; status: string }> {
Expand Down
Loading