Skip to content

Commit

Permalink
chore(dashboard): delete session cookie after termination (#82)
Browse files Browse the repository at this point in the history
* chore(dashboard): delete session cookie after termination

* chore(dashboard): remove Compute type from this PR
  • Loading branch information
andypf authored Feb 28, 2025
1 parent 8fcd13b commit eb75f67
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 55 deletions.
3 changes: 2 additions & 1 deletion apps/aurora-portal/src/client/Shell/AuthProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ interface AuthApi {
interface State {
user: User | null
error: string | null
reason?: string | null
isLoading: boolean
}

Expand All @@ -36,7 +37,7 @@ const useAuthApi = (): AuthApi => {
trpcClient.identity.getAuthStatus
.query()
.then((res) => {
setAuth({ user: res.user, error: null, isLoading: false })
setAuth({ user: res.user, error: null, isLoading: false, reason: res.reason })
})
.catch((e) => setAuth({ user: null, error: e.message, isLoading: false }))
}, [])
Expand Down
4 changes: 2 additions & 2 deletions apps/aurora-portal/src/server/Identity/routers/tokenRouter.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { z } from "zod"
import { publicProcedure, protectedProcedure } from "../../trpc"
import { publicProcedure } from "../../trpc"

export const tokenRouter = {
getAuthStatus: protectedProcedure.query(async ({ ctx }) => {
getAuthStatus: publicProcedure.query(async ({ ctx }) => {
const token = ctx.openstack?.getToken()

if (!token?.authToken) {
Expand Down
54 changes: 34 additions & 20 deletions apps/aurora-portal/src/server/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ dotenv.config()
const identityEndpoint = process.env.IDENTITY_ENDPOINT
// Ensure it ends with a single slash
const normalizedEndpoint = identityEndpoint?.endsWith("/") ? identityEndpoint : `${identityEndpoint}/`
const defaultSignalOpenstackOptions = {
interfaceName: process.env.DEFAULT_ENDPOINT_INTERFACE || "internal",
debug: false,
}

export interface AuroraPortalContext extends AuroraContext {
createSession: (params: { user: string; password: string; domain: string }) => SignalOpenstackSessionType
Expand All @@ -24,17 +28,18 @@ function SessionCookie(cookieName: string, opts: CreateAuroraFastifyContextOptio
httpOnly: true,
sameSite: "strict",
expires: options?.expires || undefined,
path: "polaris-bff", // Optional: if set, must be the same for both set and del
})
},
get: () => opts.req.cookies[cookieName],

del: () => {
// Clear the cookie by setting an empty value and an immediate expiration date
opts.res.setCookie(cookieName, "", {
httpOnly: true, // Optional: to make it inaccessible via JavaScript
secure: true, // Optional: set to true for HTTPS
sameSite: "strict", // Optional: controls cross-site behavior
expires: new Date(0), // Expire immediately
secure: true, // Wichtig: gleich wie beim Setzen
httpOnly: true, // Wichtig: gleich wie beim Setzen
sameSite: "strict", // Wichtig: gleich wie beim Setzen
expires: new Date(0), // Cookie sofort ablaufen lassen
path: "polaris-bff", // Optional: falls gesetzt, muss es auch hier gleich sein
})
},
}
Expand All @@ -47,14 +52,18 @@ export async function createContext(opts: CreateAuroraFastifyContextOptions): Pr

// If we have a token, initialize the session
if (currentAuthToken) {
openstackSession = await SignalOpenstackSession(normalizedEndpoint, {
auth: {
identity: {
methods: ["token"],
token: { id: currentAuthToken },
openstackSession = await SignalOpenstackSession(
normalizedEndpoint,
{
auth: {
identity: {
methods: ["token"],
token: { id: currentAuthToken },
},
},
},
}).catch(() => {
defaultSignalOpenstackOptions
).catch(() => {
// If the token is invalid, clear the cookie
sessionCookie.del()
return undefined
Expand All @@ -65,14 +74,18 @@ export async function createContext(opts: CreateAuroraFastifyContextOptions): Pr

// Create a new session (Login)
const createSession: AuroraPortalContext["createSession"] = async (params) => {
openstackSession = await SignalOpenstackSession(normalizedEndpoint, {
auth: {
identity: {
methods: ["password"],
password: { user: { name: params.user, password: params.password, domain: { name: params.domain } } },
openstackSession = await SignalOpenstackSession(
normalizedEndpoint,
{
auth: {
identity: {
methods: ["password"],
password: { user: { name: params.user, password: params.password, domain: { name: params.domain } } },
},
},
},
})
defaultSignalOpenstackOptions
)
const token = openstackSession.getToken()
sessionCookie.set(token?.authToken)
return openstackSession
Expand All @@ -90,10 +103,11 @@ export async function createContext(opts: CreateAuroraFastifyContextOptions): Pr
// Terminate the current session (Logout)
const terminateSession = async () => {
if (openstackSession) {
await openstackSession.terminate()
openstackSession = undefined
await openstackSession.terminate().finally(() => {
openstackSession = undefined
sessionCookie.del()
})
}
sessionCookie.del()
}

return {
Expand Down
48 changes: 21 additions & 27 deletions packages/signal-openstack/src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as client from "./client"

describe("client", () => {
describe("GET", () => {
beforeAll(() => {
beforeEach(() => {
global.fetch = vi.fn().mockResolvedValue({ ok: true, json: () => Promise.resolve({}) })
})

Expand Down Expand Up @@ -58,18 +58,13 @@ describe("client", () => {
global.fetch = vi.fn().mockResolvedValue({ ok: false, statusText: "error", status: 500 })
await expect(client.get("/", { host: "http://localhost" })).rejects.toThrow("SignalOpenstackApiError: error")
})
})

it("should log debug info", async () => {
console.debug = vi.fn()
describe("HEAD", () => {
beforeEach(() => {
global.fetch = vi.fn().mockResolvedValue({ ok: true, json: () => Promise.resolve({}) })
await client.get("/", { host: "http://localhost", debug: true })
expect(console.debug).toHaveBeenCalledWith(
"===Signal Openstack Debug: url = http://localhost/, headers = {}, body = undefined"
)
})
})

describe("HEAD", () => {
it("should respond to head", async () => {
expect(client.head).toBeDefined()
})
Expand Down Expand Up @@ -115,15 +110,6 @@ describe("client", () => {
await expect(client.head("/", { host: "http://localhost" })).rejects.toThrow("SignalOpenstackApiError: error")
})

it("should log debug info", async () => {
console.debug = vi.fn()
global.fetch = vi.fn().mockResolvedValue({ ok: true, json: () => Promise.resolve({}) })
await client.head("/", { host: "http://localhost", debug: true })
expect(console.debug).toHaveBeenCalledWith(
"===Signal Openstack Debug: url = http://localhost/, headers = {}, body = undefined"
)
})

it("should return a promise", async () => {
expect(client.head("/", { host: "http://localhost" })).toBeInstanceOf(Promise)
})
Expand Down Expand Up @@ -172,18 +158,13 @@ describe("client", () => {
global.fetch = vi.fn().mockResolvedValue({ ok: false, statusText: "error", status: 500 })
await expect(client.head("/", { host: "http://localhost" })).rejects.toThrow("SignalOpenstackApiError: error")
})
})

it("should log debug info", async () => {
console.debug = vi.fn()
describe("DEL", () => {
beforeEach(() => {
global.fetch = vi.fn().mockResolvedValue({ ok: true, json: () => Promise.resolve({}) })
await client.head("/", { host: "http://localhost", debug: true })
expect(console.debug).toHaveBeenCalledWith(
"===Signal Openstack Debug: url = http://localhost/, headers = {}, body = undefined"
)
})
})

describe("DEL", () => {
it("should respond to del", async () => {
expect(client.del).toBeDefined()
})
Expand Down Expand Up @@ -234,7 +215,20 @@ describe("client", () => {
global.fetch = vi.fn().mockResolvedValue({ ok: true, json: () => Promise.resolve({}) })
await client.del("/", { host: "http://localhost", debug: true })
expect(console.debug).toHaveBeenCalledWith(
"===Signal Openstack Debug: url = http://localhost/, headers = {}, body = undefined"
"===Signal Openstack Debug: ",
JSON.stringify(
{
method: "DELETE",
path: "/",
options: {
host: "http://localhost",
debug: true,
},
url: "http://localhost/",
},
null,
2
)
)
})
})
Expand Down
4 changes: 1 addition & 3 deletions packages/signal-openstack/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ const request = ({ method, path, options = {} }: RequestParams) => {
}

if (options.debug) {
console.debug(
`===Signal Openstack Debug: url = ${url.toString()}, headers = ${JSON.stringify({ ...options.headers }, null, 2)}, body = ${body}`
)
console.debug(`===Signal Openstack Debug: `, JSON.stringify({ method, path, options, url }, null, 2))
}

return fetch(url.toString(), {
Expand Down
2 changes: 1 addition & 1 deletion packages/signal-openstack/src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export function SignalOpenstackService(
const serviceEndpoint = token.serviceEndpoint(name, { interfaceName, region })

if (debug) {
console.debug(`===Signal Openstack Debug: serviceEndpoint `, serviceEndpoint)
console.debug("===Signal Openstack Debug: ", { name, region, interfaceName, serviceEndpoint })
}

if (serviceEndpoint === undefined || serviceEndpoint === null) {
Expand Down
2 changes: 1 addition & 1 deletion packages/signal-openstack/src/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export async function SignalOpenstackSession(
// public functions
async function terminate() {
if (isValid()) {
await del(endpoint, { headers: { "X-Auth-Token": token!.authToken } })
await del(endpoint, { headers: { "X-Auth-Token": token!.authToken, "X-Subject-Token": token!.authToken } })
}
token = undefined
}
Expand Down

0 comments on commit eb75f67

Please sign in to comment.