LoginSignup
2
0

More than 1 year has passed since last update.

rustでGoogleCloudStorageの署名付きURLを作成する

Posted at

はじめに

rustではGCPのクライアントライブラリがないので署名付きURLの生成は独自に実装する必要があります。

ドキュメントを見ると自前で実装するのは大変そうなのでcrateを使用します。

cloud-storageはGCS操作を一通り網羅しているのでさくっと使うにはこれで十分かと思われます。
しかし署名付きURLの生成するためにはメタデータをGCSから取得する必要があり、少し扱いづらいので断念しました。
https://github.com/ThouCheese/cloud-storage-rs/blob/cee9786d7aae821e0615d2420e94434f4dce41eb/src/resources/object.rs#L749

今回は軽量なtame-gcsを使用します

tame-gcs = { version = "0.10.0", features = ["signing"] }
url = "2.2"

やりかた

GCPで必要な権限を付与したサービスアカウントを用意しておきます。

fn signed_url() -> Result<url::Url, tame_gcs::Error> {
    let sa = ServiceAccount::load_json_file("./service-account.json")?;
    let options = SignedUrlOptional::default();
    let bucket = BucketName::try_from("some-bucket")?;
    let object = ObjectName::try_from("some-object")?;
    let url_signer = UrlSigner::with_ring();
    let signed_url = url_signer.generate(&sa, &(&bucket, &object), options)?;
    Ok(signed_url)
}

exampleにありますがSignedUrlOptionalでメソッドや有効期限なども設定できます。

ServiceAccountではなくKeyProviderトレイトを利用すると、秘密鍵とメールアドレスだけで生成することもできます。

/// Provides the details needed for signing a URL
pub trait KeyProvider {
    /// The actual key used to sign the URL
    fn key(&self) -> Key<'_>;
    /// The identifier for the key author, in GCP this is the email
    /// address of the service account
    fn authorizer(&self) -> &str;
}

https://github.com/EmbarkStudios/tame-gcs/blob/cbbcf29d40533edfc8c930a22249a332cfb0aaf9/src/signing.rs#L69

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0