Skip to content
Merged
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
29 changes: 29 additions & 0 deletions database/migrations/0001_01_01_000000_create_api_tokens_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
public function up(): void
{
Schema::create('api_tokens', function (Blueprint $table): void {
$table->uuid('id')->primary();
$table->string('name')->index();
$table->string('token_hash', 64)->unique();
$table->timestamp('last_used_at')->nullable();
$table->unsignedBigInteger('request_count')->default(0);
$table->timestamp('expires_at')->nullable();
$table->timestamp('revoked_at')->nullable();
$table->timestamps();
});
}

public function down(): void
{
Schema::dropIfExists('api_tokens');
}
};
80 changes: 80 additions & 0 deletions src/ApiToken.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

declare(strict_types=1);

namespace ArtisanBuild\BuiltForCloud;

use ArtisanBuild\BuiltForCloud\Database\Factories\ApiTokenFactory;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
* @property string $id
* @property string $name
* @property string $token_hash
* @property CarbonInterface|null $last_used_at
* @property int $request_count
* @property CarbonInterface|null $expires_at
* @property CarbonInterface|null $revoked_at
* @property CarbonInterface|null $created_at
* @property CarbonInterface|null $updated_at
*
* @method static ApiTokenFactory factory($count = null, $state = [])
*/
final class ApiToken extends Model
{
/** @use HasFactory<ApiTokenFactory> */
use HasFactory;

use HasUuids;

public $incrementing = false;

protected $keyType = 'string';

/**
* @var list<string>
*/
protected $fillable = [
'id',
'name',
'token_hash',
'last_used_at',
'request_count',
'expires_at',
'revoked_at',
];

/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'last_used_at' => 'datetime',
'expires_at' => 'datetime',
'revoked_at' => 'datetime',
'request_count' => 'integer',
];
}

/**
* @param Builder<ApiToken> $query
* @return Builder<ApiToken>
*/
public function scopeResolvable(Builder $query): Builder
{
return $query->where(function (Builder $query): void {
$query->whereNull('expires_at')
->orWhere('expires_at', '>', now());
});
}

protected static function newFactory(): ApiTokenFactory
{
return ApiTokenFactory::new();
}
}
30 changes: 30 additions & 0 deletions src/Database/Factories/ApiTokenFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace ArtisanBuild\BuiltForCloud\Database\Factories;

use ArtisanBuild\BuiltForCloud\ApiToken;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
* @extends Factory<ApiToken>
*/
final class ApiTokenFactory extends Factory
{
protected $model = ApiToken::class;

/**
* @return array{name: string, token_hash: string, expires_at: null}
*/
public function definition(): array
{
$plaintext = bin2hex(random_bytes(32));

return [
'name' => fake()->word(),
'token_hash' => hash('sha256', $plaintext),
'expires_at' => null,
];
}
}
13 changes: 13 additions & 0 deletions src/GeneratedToken.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace ArtisanBuild\BuiltForCloud;

final readonly class GeneratedToken
{
public function __construct(
public string $plaintext,
public string $hash,
) {}
}
18 changes: 18 additions & 0 deletions src/TokenGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace ArtisanBuild\BuiltForCloud;

final class TokenGenerator
{
public function generate(): GeneratedToken
{
$plaintext = (string) config('built-for-cloud.token_prefix').bin2hex(random_bytes(32));

return new GeneratedToken(
plaintext: $plaintext,
hash: hash('sha256', $plaintext),
);
}
}
89 changes: 89 additions & 0 deletions src/TokenRegistry.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

declare(strict_types=1);

namespace ArtisanBuild\BuiltForCloud;

use Carbon\CarbonInterface;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

final class TokenRegistry
{
public const FALLBACK = 'fallback';

public function resolve(string $bearer): ?string
{
if ($bearer === '') {
return null;
}

$fallback = config('built-for-cloud.fallback_token');

if ($fallback !== null && $fallback !== '' && hash_equals(hash('sha256', (string) $fallback), hash('sha256', $bearer))) {
return self::FALLBACK;
}

/** @var ApiToken|null $row */
$row = ApiToken::query()
->where('token_hash', hash('sha256', $bearer))
->resolvable()
->first();

if ($row === null) {
return null;
}

ApiToken::query()->whereKey($row->getKey())->update([
'request_count' => DB::raw('request_count + 1'),
'last_used_at' => now(),
]);

return $row->name;
}

public function store(string $name, string $hash, ?CarbonInterface $expiresAt = null): ApiToken
{
if ($name === self::FALLBACK) {
throw new InvalidArgumentException('The fallback token name is reserved.');
}

if (! preg_match('/^[0-9a-f]{64}$/', $hash)) {
throw new InvalidArgumentException('A token hash must be a sha256 hex digest.');
}

return ApiToken::query()->create([
'name' => $name,
'token_hash' => $hash,
'expires_at' => $expiresAt,
'revoked_at' => null,
]);
}

public function rotate(string $name, string $newHash, bool $emergency = false): ApiToken
{
$newToken = $this->store($name, $newHash);
$expiresAt = $emergency ? now() : now()->addHour();

ApiToken::query()
->where('name', $name)
->whereKeyNot($newToken->getKey())
->resolvable()
->update(['expires_at' => $expiresAt]);

return $newToken;
}

public function revoke(string $name): int
{
$now = now();

return ApiToken::query()
->where('name', $name)
->resolvable()
->update([
'expires_at' => $now,
'revoked_at' => $now,
]);
}
}
Loading