Struct qiniu_credential::GotCredential
source · pub struct GotCredential(_);
Expand description
获取的认证信息
该数据结构目前和认证信息相同,可以和认证信息相互转换,但之后可能会添加更多字段
Implementations§
source§impl GotCredential
impl GotCredential
sourcepub fn credential(&self) -> &Credential
pub fn credential(&self) -> &Credential
获取认证信息
sourcepub fn credential_mut(&mut self) -> &mut Credential
pub fn credential_mut(&mut self) -> &mut Credential
获取认证信息的可变引用
Methods from Deref<Target = Credential>§
sourcepub fn access_key(&self) -> &AccessKey
pub fn access_key(&self) -> &AccessKey
获取认证信息的 AccessKey
Examples found in repository?
src/lib.rs (line 221)
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
fn sign_within<E, F: FnOnce(&mut Hmac<Sha1>) -> Result<(), E>>(&self, f: F) -> Result<String, E> {
let signature = generate_base64ed_hmac_sha1_digest_within(self.secret_key(), f)?;
Ok(self.access_key().to_string() + ":" + &signature)
}
/// 使用七牛签名算法对数据进行签名,并同时给出签名和原数据
///
/// 参考[上传凭证的签名算法文档](https://developer.qiniu.com/kodo/manual/1208/upload-token)
///
/// ```
/// use qiniu_credential::{Credential, prelude::*};
/// use std::io::Cursor;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// assert_eq!(
/// credential.get(Default::default())?.sign_with_data(b"hello"),
/// "abcdefghklmnopq:BZYt5uVRy1RVt5ZTXbaIt2ROVMA=:aGVsbG8="
/// );
/// # Ok(())
/// # }
/// ```
pub fn sign_with_data(&self, data: &[u8]) -> String {
let encoded_data = base64::urlsafe(data);
self.sign(encoded_data.as_bytes()) + ":" + &encoded_data
}
/// 使用七牛签名算法 V1 对 HTTP 请求(请求体为内存数据)进行签名,返回 Authorization 的值
///
/// ```
/// use qiniu_credential::{Credential, HeaderValue, prelude::*};
/// use mime::APPLICATION_WWW_FORM_URLENCODED;
/// use std::io::Cursor;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let authorization = credential
/// .get(Default::default())?
/// .authorization_v1_for_request(
/// &"http://upload.qiniup.com/".parse()?,
/// Some(&HeaderValue::from_str(APPLICATION_WWW_FORM_URLENCODED.as_ref())?),
/// b"name=test&language=go"
/// );
/// # Ok(())
/// # }
/// ```
pub fn authorization_v1_for_request(&self, url: &Uri, content_type: Option<&HeaderValue>, body: &[u8]) -> String {
let authorization_token = sign_request_v1(self, url, content_type, body);
"QBox ".to_owned() + &authorization_token
}
/// 使用七牛签名算法 V1 对 HTTP 请求(请求体为输入流)进行签名,返回 Authorization 的值
///
/// 该方法的异步版本为 [`Credential::authorization_v1_for_request_with_async_body_reader`]。
///
/// ```
/// use qiniu_credential::{Credential, HeaderValue, prelude::*};
/// use std::io::Cursor;
/// use mime::APPLICATION_WWW_FORM_URLENCODED;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let authorization = credential
/// .get(Default::default())?
/// .authorization_v1_for_request_with_body_reader(
/// &"http://upload.qiniup.com/".parse()?,
/// Some(&HeaderValue::from_str(APPLICATION_WWW_FORM_URLENCODED.as_ref())?),
/// &mut Cursor::new(b"name=test&language=go")
/// )?;
/// # Ok(())
/// # }
/// ```
pub fn authorization_v1_for_request_with_body_reader(
&self,
url: &Uri,
content_type: Option<&HeaderValue>,
body: &mut dyn Read,
) -> IoResult<String> {
let authorization_token = sign_request_v1_with_body_reader(self, url, content_type, body)?;
Ok("QBox ".to_owned() + &authorization_token)
}
/// 使用七牛签名算法 V2 对 HTTP 请求(请求体为内存数据)进行签名,返回 Authorization 的值
///
/// ```
/// use qiniu_credential::{Credential, Method, HeaderMap, HeaderValue, prelude::*};
/// use http::header::CONTENT_TYPE;
/// use mime::APPLICATION_JSON;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let mut headers = HeaderMap::new();
/// headers.insert(CONTENT_TYPE, HeaderValue::from_str(APPLICATION_JSON.as_ref())?);
/// let authorization = credential
/// .get(Default::default())?
/// .authorization_v2_for_request(
/// &Method::GET,
/// &"http://upload.qiniup.com/".parse()?,
/// &headers,
/// b"{\"name\":\"test\"}".as_slice(),
/// );
/// # Ok(())
/// # }
/// ```
pub fn authorization_v2_for_request(&self, method: &Method, url: &Uri, headers: &HeaderMap, body: &[u8]) -> String {
let authorization_token = sign_request_v2(self, method, url, headers, body);
"Qiniu ".to_owned() + &authorization_token
}
/// 使用七牛签名算法 V2 对 HTTP 请求(请求体为输入流)进行签名,返回 Authorization 的值
///
/// 该方法的异步版本为 [`Credential::authorization_v2_for_request_with_async_body_reader`]。
///
/// ```
/// use qiniu_credential::{Credential, Method, HeaderMap, HeaderValue, prelude::*};
/// use http::header::CONTENT_TYPE;
/// use mime::APPLICATION_JSON;
/// use std::io::Cursor;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let mut headers = HeaderMap::new();
/// headers.insert(CONTENT_TYPE, HeaderValue::from_str(APPLICATION_JSON.as_ref())?);
/// let authorization = credential
/// .get(Default::default())?
/// .authorization_v2_for_request_with_body_reader(
/// &Method::GET,
/// &"http://upload.qiniup.com/".parse()?,
/// &headers,
/// &mut Cursor::new(b"{\"name\":\"test\"}")
/// )?;
/// # Ok(())
/// # }
/// ```
pub fn authorization_v2_for_request_with_body_reader(
&self,
method: &Method,
url: &Uri,
headers: &HeaderMap,
body: &mut dyn Read,
) -> IoResult<String> {
let authorization_token = sign_request_v2_with_body_reader(self, method, url, headers, body)?;
Ok("Qiniu ".to_owned() + &authorization_token)
}
/// 对对象的下载 URL 签名,可以生成私有存储空间的下载地址
///
/// ```
/// use qiniu_credential::{Credential, prelude::*};
/// use std::time::Duration;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let url = "http://www.qiniu.com/?go=1".parse()?;
/// let url = credential
/// .get(Default::default())?
/// .sign_download_url(url, Duration::from_secs(3600));
/// println!("{}", url);
/// Ok(())
/// }
/// ```
pub fn sign_download_url(&self, url: Uri, lifetime: Duration) -> Uri {
let deadline = SystemTime::now() + lifetime;
let deadline = deadline
.duration_since(UNIX_EPOCH)
.expect("Invalid UNIX Timestamp")
.as_secs();
let to_sign = append_query_pairs_to_url(url, &[("e", &deadline.to_string())]);
let signature = self.sign(to_sign.to_string().as_bytes());
return append_query_pairs_to_url(to_sign, &[("token", &signature)]);
fn append_query_pairs_to_url(url: Uri, pairs: &[(&str, &str)]) -> Uri {
let path_string = url.path().to_owned();
let query_string = url.query().unwrap_or_default().to_owned();
let mut serializer = form_urlencoded::Serializer::new(query_string);
for (key, value) in pairs.iter() {
serializer.append_pair(key, value);
}
let query_string = serializer.finish();
let mut path_and_query = path_string;
if !query_string.is_empty() {
path_and_query.push('?');
path_and_query.push_str(&query_string);
}
let parts = url.into_parts();
let mut builder = Uri::builder();
if let Some(scheme) = parts.scheme {
builder = builder.scheme(scheme);
}
if let Some(authority) = parts.authority {
builder = builder.authority(authority);
}
builder.path_and_query(&path_and_query).build().unwrap()
}
}
#[allow(dead_code)]
fn assert() {
assert_impl!(Send: Self);
assert_impl!(Sync: Self);
}
}
#[cfg(feature = "async")]
impl Credential {
/// 使用七牛签名算法对异步输入流数据进行签名
///
/// 参考[管理凭证的签名算法文档](https://developer.qiniu.com/kodo/manual/1201/access-token)
///
/// ```
/// use qiniu_credential::{Credential, prelude::*};
/// use futures_lite::io::Cursor;
/// # async fn f() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// assert_eq!(
/// credential
/// .async_get(Default::default()).await?
/// .sign_async_reader(&mut Cursor::new(b"world")).await?,
/// "abcdefghklmnopq:VjgXt0P_nCxHuaTfiFz-UjDJ1AQ="
/// );
/// # Ok(())
/// # }
/// ```
#[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
pub async fn sign_async_reader(&self, reader: &mut (dyn AsyncRead + Send + Unpin)) -> IoResult<String> {
let mut hmac = new_hmac_sha1(self.secret_key());
copy_async_reader_to_hmac_sha1(&mut hmac, reader).await?;
Ok(base64ed_hmac_sha1_with_access_key(self.access_key().to_string(), hmac))
}
/// 使用七牛签名算法 V1 对 HTTP 请求(请求体为异步输入流)进行签名,返回 Authorization 的值
///
/// ```
/// use qiniu_credential::{Credential, HeaderValue, prelude::*};
/// use mime::APPLICATION_WWW_FORM_URLENCODED;
/// use futures_lite::io::Cursor;
/// # async fn f() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let authorization = credential
/// .async_get(Default::default()).await?
/// .authorization_v1_for_request_with_async_body_reader(
/// &"http://upload.qiniup.com/".parse()?,
/// Some(&HeaderValue::from_str(APPLICATION_WWW_FORM_URLENCODED.as_ref())?),
/// &mut Cursor::new(b"name=test&language=go")
/// ).await?;
/// # Ok(())
/// # }
/// ```
#[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
pub async fn authorization_v1_for_request_with_async_body_reader(
&self,
url: &Uri,
content_type: Option<&HeaderValue>,
body: &mut (dyn AsyncRead + Send + Unpin),
) -> IoResult<String> {
let authorization_token = sign_request_v1_with_async_body_reader(self, url, content_type, body).await?;
Ok("QBox ".to_owned() + &authorization_token)
}
/// 使用七牛签名算法 V2 对 HTTP 请求(请求体为异步输入流)进行签名,返回 Authorization 的值
///
/// ```
/// use qiniu_credential::{Credential, Method, HeaderMap, HeaderValue, prelude::*};
/// use http::header::CONTENT_TYPE;
/// use mime::APPLICATION_JSON;
/// use futures_lite::io::Cursor;
/// #[async_std::main]
/// # async fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let mut headers = HeaderMap::new();
/// headers.insert(CONTENT_TYPE, HeaderValue::from_str(APPLICATION_JSON.as_ref())?);
/// let authorization = credential
/// .async_get(Default::default()).await?
/// .authorization_v2_for_request_with_async_body_reader(
/// &Method::GET,
/// &"http://upload.qiniup.com/".parse()?,
/// &headers,
/// &mut Cursor::new(b"{\"name\":\"test\"}")
/// ).await?;
/// # Ok(())
/// # }
/// ```
#[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
pub async fn authorization_v2_for_request_with_async_body_reader(
&self,
method: &Method,
url: &Uri,
headers: &HeaderMap,
body: &mut (dyn AsyncRead + Send + Unpin),
) -> IoResult<String> {
let authorization_token = sign_request_v2_with_async_body_reader(self, method, url, headers, body).await?;
Ok("Qiniu ".to_owned() + &authorization_token)
}
}
fn sign_request_v1(cred: &Credential, url: &Uri, content_type: Option<&HeaderValue>, body: &[u8]) -> String {
cred.sign_within::<IoError, _>(|hmac| {
_sign_request_v1_without_body(hmac, url);
if let Some(content_type) = content_type {
if !body.is_empty() && will_push_body_v1(content_type) {
hmac.update(body);
}
}
Ok(())
})
.unwrap()
}
fn sign_request_v1_with_body_reader(
cred: &Credential,
url: &Uri,
content_type: Option<&HeaderValue>,
body: &mut dyn Read,
) -> IoResult<String> {
cred.sign_within(|hmac| {
_sign_request_v1_without_body(hmac, url);
if let Some(content_type) = content_type {
if will_push_body_v1(content_type) {
copy(body, hmac)?;
}
}
Ok(())
})
}
fn _sign_request_v1_without_body(digest: &mut Hmac<Sha1>, url: &Uri) {
digest.update(url.path().as_bytes());
if let Some(query) = url.query() {
if !query.is_empty() {
digest.update(b"?");
digest.update(query.as_bytes());
}
}
digest.update(b"\n");
}
fn sign_request_v2(cred: &Credential, method: &Method, url: &Uri, headers: &HeaderMap, body: &[u8]) -> String {
cred.sign_within::<IoError, _>(|hmac| {
_sign_request_v2_without_body(hmac, method, url, headers);
if let Some(content_type) = headers.get(CONTENT_TYPE) {
if will_push_body_v2(content_type) {
hmac.update(body);
}
}
Ok(())
})
.unwrap()
}
fn sign_request_v2_with_body_reader(
cred: &Credential,
method: &Method,
url: &Uri,
headers: &HeaderMap,
body: &mut dyn Read,
) -> IoResult<String> {
cred.sign_within(|hmac| {
_sign_request_v2_without_body(hmac, method, url, headers);
if let Some(content_type) = headers.get(CONTENT_TYPE) {
if will_push_body_v2(content_type) {
copy(body, hmac)?;
}
}
Ok(())
})
}
fn _sign_request_v2_without_body(digest: &mut Hmac<Sha1>, method: &Method, url: &Uri, headers: &HeaderMap) {
digest.update(method.as_str().as_bytes());
digest.update(b" ");
digest.update(url.path().as_bytes());
if let Some(query) = url.query() {
if !query.is_empty() {
digest.update(b"?");
digest.update(query.as_bytes());
}
}
if let Some(host) = url.host() {
digest.update(b"\nHost: ");
digest.update(host.as_bytes());
}
if let Some(port) = url.port() {
digest.update(b":");
digest.update(port.to_string().as_bytes());
}
digest.update(b"\n");
if let Some(content_type) = headers.get(CONTENT_TYPE) {
digest.update(b"Content-Type: ");
digest.update(content_type.as_bytes());
digest.update(b"\n");
}
_sign_data_for_x_qiniu_headers(digest, headers);
digest.update(b"\n");
return;
fn _sign_data_for_x_qiniu_headers(digest: &mut Hmac<Sha1>, headers: &HeaderMap) {
let mut x_qiniu_headers = headers
.iter()
.map(|(key, value)| (make_header_name(key.as_str().into()), value.as_bytes()))
.filter(|(key, _)| key.len() > "X-Qiniu-".len())
.filter(|(key, _)| key.starts_with("X-Qiniu-"))
.collect::<Vec<_>>();
if x_qiniu_headers.is_empty() {
return;
}
x_qiniu_headers.sort_unstable();
for (header_key, header_value) in x_qiniu_headers {
digest.update(header_key.as_bytes());
digest.update(b": ");
digest.update(header_value);
digest.update(b"\n");
}
}
}
fn generate_base64ed_hmac_sha1_digest_within<E, F: FnOnce(&mut Hmac<Sha1>) -> Result<(), E>>(
secret_key: &str,
f: F,
) -> Result<String, E> {
let mut hmac = new_hmac_sha1(secret_key);
f(&mut hmac)?;
Ok(base64ed_hmac_sha1(hmac))
}
fn new_hmac_sha1(secret_key: &str) -> Hmac<Sha1> {
Hmac::<Sha1>::new_from_slice(secret_key.as_bytes()).unwrap()
}
fn base64ed_hmac_sha1(hmac: Hmac<Sha1>) -> String {
base64::urlsafe(&hmac.finalize().into_bytes())
}
#[cfg(feature = "async")]
fn base64ed_hmac_sha1_with_access_key(access_key: String, hmac: Hmac<Sha1>) -> String {
access_key + ":" + &base64ed_hmac_sha1(hmac)
}
fn will_push_body_v1(content_type: &HeaderValue) -> bool {
APPLICATION_WWW_FORM_URLENCODED.as_ref() == content_type
}
fn will_push_body_v2(content_type: &HeaderValue) -> bool {
APPLICATION_OCTET_STREAM.as_ref() != content_type
}
#[cfg(feature = "async")]
mod async_sign {
use super::*;
use futures_lite::io::AsyncRead;
use std::task::{Context, Poll};
pub(super) async fn sign_request_v1_with_async_body_reader(
cred: &Credential,
url: &Uri,
content_type: Option<&HeaderValue>,
body: &mut (dyn AsyncRead + Send + Unpin),
) -> IoResult<String> {
let mut hmac = new_hmac_sha1(cred.secret_key());
_sign_request_v1_without_body(&mut hmac, url);
if let Some(content_type) = content_type {
if will_push_body_v1(content_type) {
copy_async_reader_to_hmac_sha1(&mut hmac, body).await?;
}
}
Ok(base64ed_hmac_sha1_with_access_key(cred.access_key().to_string(), hmac))
}
pub(super) async fn sign_request_v2_with_async_body_reader(
cred: &Credential,
method: &Method,
url: &Uri,
headers: &HeaderMap,
body: &mut (dyn AsyncRead + Send + Unpin),
) -> IoResult<String> {
let mut hmac = new_hmac_sha1(cred.secret_key());
_sign_request_v2_without_body(&mut hmac, method, url, headers);
if let Some(content_type) = headers.get(CONTENT_TYPE) {
if will_push_body_v2(content_type) {
copy_async_reader_to_hmac_sha1(&mut hmac, body).await?;
}
}
Ok(base64ed_hmac_sha1_with_access_key(cred.access_key().to_string(), hmac))
}
pub(super) async fn copy_async_reader_to_hmac_sha1(
hmac: &mut Hmac<Sha1>,
reader: &mut (dyn AsyncRead + Send + Unpin),
) -> IoResult<u64> {
use futures_lite::io::{copy as async_io_copy, AsyncWrite};
struct AsyncHmacWriter<'a>(&'a mut Hmac<Sha1>);
impl AsyncWrite for AsyncHmacWriter<'_> {
#[inline]
fn poll_write(self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &[u8]) -> Poll<IoResult<usize>> {
#[allow(unsafe_code)]
unsafe { self.get_unchecked_mut() }.0.update(buf);
Poll::Ready(Ok(buf.len()))
}
#[inline]
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<IoResult<()>> {
Poll::Ready(Ok(()))
}
#[inline]
fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<IoResult<()>> {
Poll::Ready(Ok(()))
}
}
async_io_copy(reader, &mut AsyncHmacWriter(hmac)).await
}
}
#[cfg(feature = "async")]
#[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
pub use futures_lite::AsyncRead;
#[cfg(feature = "async")]
use {
async_sign::*,
std::{future::Future, pin::Pin},
};
#[cfg(feature = "async")]
type AsyncIoResult<'a, T> = Pin<Box<dyn Future<Output = IoResult<T>> + 'a + Send>>;
/// 认证信息获取接口
#[clonable]
#[auto_impl(&, &mut, Box, Rc, Arc)]
pub trait CredentialProvider: Clone + Debug + Sync + Send {
/// 返回七牛认证信息
///
/// 该方法的异步版本为 [`Self::async_get`]。
fn get(&self, opts: GetOptions) -> IoResult<GotCredential>;
/// 异步返回七牛认证信息
#[inline]
#[cfg(feature = "async")]
#[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
fn async_get(&self, opts: GetOptions) -> AsyncIoResult<'_, GotCredential> {
Box::pin(async move { self.get(opts) })
}
}
impl CredentialProvider for Credential {
#[inline]
fn get(&self, _opts: GetOptions) -> IoResult<GotCredential> {
Ok(self.to_owned().into())
}
}
/// 获取认证信息的选项
#[derive(Copy, Clone, Debug, Default)]
pub struct GetOptions {}
/// 获取的认证信息
///
/// 该数据结构目前和认证信息相同,可以和认证信息相互转换,但之后可能会添加更多字段
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GotCredential(Credential);
impl From<GotCredential> for Credential {
#[inline]
fn from(result: GotCredential) -> Self {
result.into_credential()
}
}
impl From<Credential> for GotCredential {
#[inline]
fn from(credential: Credential) -> Self {
Self(credential)
}
}
impl GotCredential {
/// 获取认证信息
#[inline]
pub fn credential(&self) -> &Credential {
&self.0
}
/// 获取认证信息的可变引用
#[inline]
pub fn credential_mut(&mut self) -> &mut Credential {
&mut self.0
}
/// 转换为认证信息
#[inline]
pub fn into_credential(self) -> Credential {
self.0
}
}
impl Deref for GotCredential {
type Target = Credential;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for GotCredential {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl CredentialProvider for GotCredential {
#[inline]
fn get(&self, _opts: GetOptions) -> IoResult<GotCredential> {
Ok(self.to_owned())
}
}
/// 全局认证信息提供者,可以将认证信息配置在全局变量中。任何全局认证信息提供者实例都可以设置和访问全局认证信息。
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct GlobalCredentialProvider;
static GLOBAL_CREDENTIAL: Lazy<RwLock<Option<Credential>>> = Lazy::new(|| RwLock::new(None));
impl GlobalCredentialProvider {
/// 配置全局认证信息
#[inline]
pub fn setup(credential: Credential) {
let mut global_credential = GLOBAL_CREDENTIAL.write().unwrap();
*global_credential = Some(credential);
}
/// 清空全局认证信息
#[inline]
pub fn clear() {
let mut global_credential = GLOBAL_CREDENTIAL.write().unwrap();
*global_credential = None;
}
}
impl CredentialProvider for GlobalCredentialProvider {
#[inline]
fn get(&self, _opts: GetOptions) -> IoResult<GotCredential> {
if let Some(credential) = GLOBAL_CREDENTIAL.read().unwrap().as_ref() {
Ok(credential.to_owned().into())
} else {
Err(IoError::new(
IoErrorKind::Other,
"GlobalCredentialProvider is not setuped, please call GlobalCredentialProvider::setup() to do it",
))
}
}
}
impl Debug for GlobalCredentialProvider {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut d = f.debug_struct("GlobalCredentialProvider");
d.field("credential", &GLOBAL_CREDENTIAL.read().unwrap());
d.finish()
}
}
/// 环境变量认证信息提供者,可以将认证信息配置在环境变量中。
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct EnvCredentialProvider;
/// 设置七牛 AccessKey 的环境变量
pub const QINIU_ACCESS_KEY_ENV_KEY: &str = "QINIU_ACCESS_KEY";
/// 设置七牛 SecretKey 的环境变量
pub const QINIU_SECRET_KEY_ENV_KEY: &str = "QINIU_SECRET_KEY";
impl EnvCredentialProvider {
/// 配置环境变量认证信息提供者
#[inline]
pub fn setup(credential: &Credential) {
env::set_var(QINIU_ACCESS_KEY_ENV_KEY, credential.access_key().as_str());
env::set_var(QINIU_SECRET_KEY_ENV_KEY, credential.secret_key().as_str());
}
sourcepub fn secret_key(&self) -> &SecretKey
pub fn secret_key(&self) -> &SecretKey
获取认证信息的 SecretKey
Examples found in repository?
src/lib.rs (line 220)
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
fn sign_within<E, F: FnOnce(&mut Hmac<Sha1>) -> Result<(), E>>(&self, f: F) -> Result<String, E> {
let signature = generate_base64ed_hmac_sha1_digest_within(self.secret_key(), f)?;
Ok(self.access_key().to_string() + ":" + &signature)
}
/// 使用七牛签名算法对数据进行签名,并同时给出签名和原数据
///
/// 参考[上传凭证的签名算法文档](https://developer.qiniu.com/kodo/manual/1208/upload-token)
///
/// ```
/// use qiniu_credential::{Credential, prelude::*};
/// use std::io::Cursor;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// assert_eq!(
/// credential.get(Default::default())?.sign_with_data(b"hello"),
/// "abcdefghklmnopq:BZYt5uVRy1RVt5ZTXbaIt2ROVMA=:aGVsbG8="
/// );
/// # Ok(())
/// # }
/// ```
pub fn sign_with_data(&self, data: &[u8]) -> String {
let encoded_data = base64::urlsafe(data);
self.sign(encoded_data.as_bytes()) + ":" + &encoded_data
}
/// 使用七牛签名算法 V1 对 HTTP 请求(请求体为内存数据)进行签名,返回 Authorization 的值
///
/// ```
/// use qiniu_credential::{Credential, HeaderValue, prelude::*};
/// use mime::APPLICATION_WWW_FORM_URLENCODED;
/// use std::io::Cursor;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let authorization = credential
/// .get(Default::default())?
/// .authorization_v1_for_request(
/// &"http://upload.qiniup.com/".parse()?,
/// Some(&HeaderValue::from_str(APPLICATION_WWW_FORM_URLENCODED.as_ref())?),
/// b"name=test&language=go"
/// );
/// # Ok(())
/// # }
/// ```
pub fn authorization_v1_for_request(&self, url: &Uri, content_type: Option<&HeaderValue>, body: &[u8]) -> String {
let authorization_token = sign_request_v1(self, url, content_type, body);
"QBox ".to_owned() + &authorization_token
}
/// 使用七牛签名算法 V1 对 HTTP 请求(请求体为输入流)进行签名,返回 Authorization 的值
///
/// 该方法的异步版本为 [`Credential::authorization_v1_for_request_with_async_body_reader`]。
///
/// ```
/// use qiniu_credential::{Credential, HeaderValue, prelude::*};
/// use std::io::Cursor;
/// use mime::APPLICATION_WWW_FORM_URLENCODED;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let authorization = credential
/// .get(Default::default())?
/// .authorization_v1_for_request_with_body_reader(
/// &"http://upload.qiniup.com/".parse()?,
/// Some(&HeaderValue::from_str(APPLICATION_WWW_FORM_URLENCODED.as_ref())?),
/// &mut Cursor::new(b"name=test&language=go")
/// )?;
/// # Ok(())
/// # }
/// ```
pub fn authorization_v1_for_request_with_body_reader(
&self,
url: &Uri,
content_type: Option<&HeaderValue>,
body: &mut dyn Read,
) -> IoResult<String> {
let authorization_token = sign_request_v1_with_body_reader(self, url, content_type, body)?;
Ok("QBox ".to_owned() + &authorization_token)
}
/// 使用七牛签名算法 V2 对 HTTP 请求(请求体为内存数据)进行签名,返回 Authorization 的值
///
/// ```
/// use qiniu_credential::{Credential, Method, HeaderMap, HeaderValue, prelude::*};
/// use http::header::CONTENT_TYPE;
/// use mime::APPLICATION_JSON;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let mut headers = HeaderMap::new();
/// headers.insert(CONTENT_TYPE, HeaderValue::from_str(APPLICATION_JSON.as_ref())?);
/// let authorization = credential
/// .get(Default::default())?
/// .authorization_v2_for_request(
/// &Method::GET,
/// &"http://upload.qiniup.com/".parse()?,
/// &headers,
/// b"{\"name\":\"test\"}".as_slice(),
/// );
/// # Ok(())
/// # }
/// ```
pub fn authorization_v2_for_request(&self, method: &Method, url: &Uri, headers: &HeaderMap, body: &[u8]) -> String {
let authorization_token = sign_request_v2(self, method, url, headers, body);
"Qiniu ".to_owned() + &authorization_token
}
/// 使用七牛签名算法 V2 对 HTTP 请求(请求体为输入流)进行签名,返回 Authorization 的值
///
/// 该方法的异步版本为 [`Credential::authorization_v2_for_request_with_async_body_reader`]。
///
/// ```
/// use qiniu_credential::{Credential, Method, HeaderMap, HeaderValue, prelude::*};
/// use http::header::CONTENT_TYPE;
/// use mime::APPLICATION_JSON;
/// use std::io::Cursor;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let mut headers = HeaderMap::new();
/// headers.insert(CONTENT_TYPE, HeaderValue::from_str(APPLICATION_JSON.as_ref())?);
/// let authorization = credential
/// .get(Default::default())?
/// .authorization_v2_for_request_with_body_reader(
/// &Method::GET,
/// &"http://upload.qiniup.com/".parse()?,
/// &headers,
/// &mut Cursor::new(b"{\"name\":\"test\"}")
/// )?;
/// # Ok(())
/// # }
/// ```
pub fn authorization_v2_for_request_with_body_reader(
&self,
method: &Method,
url: &Uri,
headers: &HeaderMap,
body: &mut dyn Read,
) -> IoResult<String> {
let authorization_token = sign_request_v2_with_body_reader(self, method, url, headers, body)?;
Ok("Qiniu ".to_owned() + &authorization_token)
}
/// 对对象的下载 URL 签名,可以生成私有存储空间的下载地址
///
/// ```
/// use qiniu_credential::{Credential, prelude::*};
/// use std::time::Duration;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let url = "http://www.qiniu.com/?go=1".parse()?;
/// let url = credential
/// .get(Default::default())?
/// .sign_download_url(url, Duration::from_secs(3600));
/// println!("{}", url);
/// Ok(())
/// }
/// ```
pub fn sign_download_url(&self, url: Uri, lifetime: Duration) -> Uri {
let deadline = SystemTime::now() + lifetime;
let deadline = deadline
.duration_since(UNIX_EPOCH)
.expect("Invalid UNIX Timestamp")
.as_secs();
let to_sign = append_query_pairs_to_url(url, &[("e", &deadline.to_string())]);
let signature = self.sign(to_sign.to_string().as_bytes());
return append_query_pairs_to_url(to_sign, &[("token", &signature)]);
fn append_query_pairs_to_url(url: Uri, pairs: &[(&str, &str)]) -> Uri {
let path_string = url.path().to_owned();
let query_string = url.query().unwrap_or_default().to_owned();
let mut serializer = form_urlencoded::Serializer::new(query_string);
for (key, value) in pairs.iter() {
serializer.append_pair(key, value);
}
let query_string = serializer.finish();
let mut path_and_query = path_string;
if !query_string.is_empty() {
path_and_query.push('?');
path_and_query.push_str(&query_string);
}
let parts = url.into_parts();
let mut builder = Uri::builder();
if let Some(scheme) = parts.scheme {
builder = builder.scheme(scheme);
}
if let Some(authority) = parts.authority {
builder = builder.authority(authority);
}
builder.path_and_query(&path_and_query).build().unwrap()
}
}
#[allow(dead_code)]
fn assert() {
assert_impl!(Send: Self);
assert_impl!(Sync: Self);
}
}
#[cfg(feature = "async")]
impl Credential {
/// 使用七牛签名算法对异步输入流数据进行签名
///
/// 参考[管理凭证的签名算法文档](https://developer.qiniu.com/kodo/manual/1201/access-token)
///
/// ```
/// use qiniu_credential::{Credential, prelude::*};
/// use futures_lite::io::Cursor;
/// # async fn f() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// assert_eq!(
/// credential
/// .async_get(Default::default()).await?
/// .sign_async_reader(&mut Cursor::new(b"world")).await?,
/// "abcdefghklmnopq:VjgXt0P_nCxHuaTfiFz-UjDJ1AQ="
/// );
/// # Ok(())
/// # }
/// ```
#[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
pub async fn sign_async_reader(&self, reader: &mut (dyn AsyncRead + Send + Unpin)) -> IoResult<String> {
let mut hmac = new_hmac_sha1(self.secret_key());
copy_async_reader_to_hmac_sha1(&mut hmac, reader).await?;
Ok(base64ed_hmac_sha1_with_access_key(self.access_key().to_string(), hmac))
}
/// 使用七牛签名算法 V1 对 HTTP 请求(请求体为异步输入流)进行签名,返回 Authorization 的值
///
/// ```
/// use qiniu_credential::{Credential, HeaderValue, prelude::*};
/// use mime::APPLICATION_WWW_FORM_URLENCODED;
/// use futures_lite::io::Cursor;
/// # async fn f() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let authorization = credential
/// .async_get(Default::default()).await?
/// .authorization_v1_for_request_with_async_body_reader(
/// &"http://upload.qiniup.com/".parse()?,
/// Some(&HeaderValue::from_str(APPLICATION_WWW_FORM_URLENCODED.as_ref())?),
/// &mut Cursor::new(b"name=test&language=go")
/// ).await?;
/// # Ok(())
/// # }
/// ```
#[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
pub async fn authorization_v1_for_request_with_async_body_reader(
&self,
url: &Uri,
content_type: Option<&HeaderValue>,
body: &mut (dyn AsyncRead + Send + Unpin),
) -> IoResult<String> {
let authorization_token = sign_request_v1_with_async_body_reader(self, url, content_type, body).await?;
Ok("QBox ".to_owned() + &authorization_token)
}
/// 使用七牛签名算法 V2 对 HTTP 请求(请求体为异步输入流)进行签名,返回 Authorization 的值
///
/// ```
/// use qiniu_credential::{Credential, Method, HeaderMap, HeaderValue, prelude::*};
/// use http::header::CONTENT_TYPE;
/// use mime::APPLICATION_JSON;
/// use futures_lite::io::Cursor;
/// #[async_std::main]
/// # async fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let mut headers = HeaderMap::new();
/// headers.insert(CONTENT_TYPE, HeaderValue::from_str(APPLICATION_JSON.as_ref())?);
/// let authorization = credential
/// .async_get(Default::default()).await?
/// .authorization_v2_for_request_with_async_body_reader(
/// &Method::GET,
/// &"http://upload.qiniup.com/".parse()?,
/// &headers,
/// &mut Cursor::new(b"{\"name\":\"test\"}")
/// ).await?;
/// # Ok(())
/// # }
/// ```
#[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
pub async fn authorization_v2_for_request_with_async_body_reader(
&self,
method: &Method,
url: &Uri,
headers: &HeaderMap,
body: &mut (dyn AsyncRead + Send + Unpin),
) -> IoResult<String> {
let authorization_token = sign_request_v2_with_async_body_reader(self, method, url, headers, body).await?;
Ok("Qiniu ".to_owned() + &authorization_token)
}
}
fn sign_request_v1(cred: &Credential, url: &Uri, content_type: Option<&HeaderValue>, body: &[u8]) -> String {
cred.sign_within::<IoError, _>(|hmac| {
_sign_request_v1_without_body(hmac, url);
if let Some(content_type) = content_type {
if !body.is_empty() && will_push_body_v1(content_type) {
hmac.update(body);
}
}
Ok(())
})
.unwrap()
}
fn sign_request_v1_with_body_reader(
cred: &Credential,
url: &Uri,
content_type: Option<&HeaderValue>,
body: &mut dyn Read,
) -> IoResult<String> {
cred.sign_within(|hmac| {
_sign_request_v1_without_body(hmac, url);
if let Some(content_type) = content_type {
if will_push_body_v1(content_type) {
copy(body, hmac)?;
}
}
Ok(())
})
}
fn _sign_request_v1_without_body(digest: &mut Hmac<Sha1>, url: &Uri) {
digest.update(url.path().as_bytes());
if let Some(query) = url.query() {
if !query.is_empty() {
digest.update(b"?");
digest.update(query.as_bytes());
}
}
digest.update(b"\n");
}
fn sign_request_v2(cred: &Credential, method: &Method, url: &Uri, headers: &HeaderMap, body: &[u8]) -> String {
cred.sign_within::<IoError, _>(|hmac| {
_sign_request_v2_without_body(hmac, method, url, headers);
if let Some(content_type) = headers.get(CONTENT_TYPE) {
if will_push_body_v2(content_type) {
hmac.update(body);
}
}
Ok(())
})
.unwrap()
}
fn sign_request_v2_with_body_reader(
cred: &Credential,
method: &Method,
url: &Uri,
headers: &HeaderMap,
body: &mut dyn Read,
) -> IoResult<String> {
cred.sign_within(|hmac| {
_sign_request_v2_without_body(hmac, method, url, headers);
if let Some(content_type) = headers.get(CONTENT_TYPE) {
if will_push_body_v2(content_type) {
copy(body, hmac)?;
}
}
Ok(())
})
}
fn _sign_request_v2_without_body(digest: &mut Hmac<Sha1>, method: &Method, url: &Uri, headers: &HeaderMap) {
digest.update(method.as_str().as_bytes());
digest.update(b" ");
digest.update(url.path().as_bytes());
if let Some(query) = url.query() {
if !query.is_empty() {
digest.update(b"?");
digest.update(query.as_bytes());
}
}
if let Some(host) = url.host() {
digest.update(b"\nHost: ");
digest.update(host.as_bytes());
}
if let Some(port) = url.port() {
digest.update(b":");
digest.update(port.to_string().as_bytes());
}
digest.update(b"\n");
if let Some(content_type) = headers.get(CONTENT_TYPE) {
digest.update(b"Content-Type: ");
digest.update(content_type.as_bytes());
digest.update(b"\n");
}
_sign_data_for_x_qiniu_headers(digest, headers);
digest.update(b"\n");
return;
fn _sign_data_for_x_qiniu_headers(digest: &mut Hmac<Sha1>, headers: &HeaderMap) {
let mut x_qiniu_headers = headers
.iter()
.map(|(key, value)| (make_header_name(key.as_str().into()), value.as_bytes()))
.filter(|(key, _)| key.len() > "X-Qiniu-".len())
.filter(|(key, _)| key.starts_with("X-Qiniu-"))
.collect::<Vec<_>>();
if x_qiniu_headers.is_empty() {
return;
}
x_qiniu_headers.sort_unstable();
for (header_key, header_value) in x_qiniu_headers {
digest.update(header_key.as_bytes());
digest.update(b": ");
digest.update(header_value);
digest.update(b"\n");
}
}
}
fn generate_base64ed_hmac_sha1_digest_within<E, F: FnOnce(&mut Hmac<Sha1>) -> Result<(), E>>(
secret_key: &str,
f: F,
) -> Result<String, E> {
let mut hmac = new_hmac_sha1(secret_key);
f(&mut hmac)?;
Ok(base64ed_hmac_sha1(hmac))
}
fn new_hmac_sha1(secret_key: &str) -> Hmac<Sha1> {
Hmac::<Sha1>::new_from_slice(secret_key.as_bytes()).unwrap()
}
fn base64ed_hmac_sha1(hmac: Hmac<Sha1>) -> String {
base64::urlsafe(&hmac.finalize().into_bytes())
}
#[cfg(feature = "async")]
fn base64ed_hmac_sha1_with_access_key(access_key: String, hmac: Hmac<Sha1>) -> String {
access_key + ":" + &base64ed_hmac_sha1(hmac)
}
fn will_push_body_v1(content_type: &HeaderValue) -> bool {
APPLICATION_WWW_FORM_URLENCODED.as_ref() == content_type
}
fn will_push_body_v2(content_type: &HeaderValue) -> bool {
APPLICATION_OCTET_STREAM.as_ref() != content_type
}
#[cfg(feature = "async")]
mod async_sign {
use super::*;
use futures_lite::io::AsyncRead;
use std::task::{Context, Poll};
pub(super) async fn sign_request_v1_with_async_body_reader(
cred: &Credential,
url: &Uri,
content_type: Option<&HeaderValue>,
body: &mut (dyn AsyncRead + Send + Unpin),
) -> IoResult<String> {
let mut hmac = new_hmac_sha1(cred.secret_key());
_sign_request_v1_without_body(&mut hmac, url);
if let Some(content_type) = content_type {
if will_push_body_v1(content_type) {
copy_async_reader_to_hmac_sha1(&mut hmac, body).await?;
}
}
Ok(base64ed_hmac_sha1_with_access_key(cred.access_key().to_string(), hmac))
}
pub(super) async fn sign_request_v2_with_async_body_reader(
cred: &Credential,
method: &Method,
url: &Uri,
headers: &HeaderMap,
body: &mut (dyn AsyncRead + Send + Unpin),
) -> IoResult<String> {
let mut hmac = new_hmac_sha1(cred.secret_key());
_sign_request_v2_without_body(&mut hmac, method, url, headers);
if let Some(content_type) = headers.get(CONTENT_TYPE) {
if will_push_body_v2(content_type) {
copy_async_reader_to_hmac_sha1(&mut hmac, body).await?;
}
}
Ok(base64ed_hmac_sha1_with_access_key(cred.access_key().to_string(), hmac))
}
pub(super) async fn copy_async_reader_to_hmac_sha1(
hmac: &mut Hmac<Sha1>,
reader: &mut (dyn AsyncRead + Send + Unpin),
) -> IoResult<u64> {
use futures_lite::io::{copy as async_io_copy, AsyncWrite};
struct AsyncHmacWriter<'a>(&'a mut Hmac<Sha1>);
impl AsyncWrite for AsyncHmacWriter<'_> {
#[inline]
fn poll_write(self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &[u8]) -> Poll<IoResult<usize>> {
#[allow(unsafe_code)]
unsafe { self.get_unchecked_mut() }.0.update(buf);
Poll::Ready(Ok(buf.len()))
}
#[inline]
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<IoResult<()>> {
Poll::Ready(Ok(()))
}
#[inline]
fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<IoResult<()>> {
Poll::Ready(Ok(()))
}
}
async_io_copy(reader, &mut AsyncHmacWriter(hmac)).await
}
}
#[cfg(feature = "async")]
#[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
pub use futures_lite::AsyncRead;
#[cfg(feature = "async")]
use {
async_sign::*,
std::{future::Future, pin::Pin},
};
#[cfg(feature = "async")]
type AsyncIoResult<'a, T> = Pin<Box<dyn Future<Output = IoResult<T>> + 'a + Send>>;
/// 认证信息获取接口
#[clonable]
#[auto_impl(&, &mut, Box, Rc, Arc)]
pub trait CredentialProvider: Clone + Debug + Sync + Send {
/// 返回七牛认证信息
///
/// 该方法的异步版本为 [`Self::async_get`]。
fn get(&self, opts: GetOptions) -> IoResult<GotCredential>;
/// 异步返回七牛认证信息
#[inline]
#[cfg(feature = "async")]
#[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
fn async_get(&self, opts: GetOptions) -> AsyncIoResult<'_, GotCredential> {
Box::pin(async move { self.get(opts) })
}
}
impl CredentialProvider for Credential {
#[inline]
fn get(&self, _opts: GetOptions) -> IoResult<GotCredential> {
Ok(self.to_owned().into())
}
}
/// 获取认证信息的选项
#[derive(Copy, Clone, Debug, Default)]
pub struct GetOptions {}
/// 获取的认证信息
///
/// 该数据结构目前和认证信息相同,可以和认证信息相互转换,但之后可能会添加更多字段
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GotCredential(Credential);
impl From<GotCredential> for Credential {
#[inline]
fn from(result: GotCredential) -> Self {
result.into_credential()
}
}
impl From<Credential> for GotCredential {
#[inline]
fn from(credential: Credential) -> Self {
Self(credential)
}
}
impl GotCredential {
/// 获取认证信息
#[inline]
pub fn credential(&self) -> &Credential {
&self.0
}
/// 获取认证信息的可变引用
#[inline]
pub fn credential_mut(&mut self) -> &mut Credential {
&mut self.0
}
/// 转换为认证信息
#[inline]
pub fn into_credential(self) -> Credential {
self.0
}
}
impl Deref for GotCredential {
type Target = Credential;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for GotCredential {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl CredentialProvider for GotCredential {
#[inline]
fn get(&self, _opts: GetOptions) -> IoResult<GotCredential> {
Ok(self.to_owned())
}
}
/// 全局认证信息提供者,可以将认证信息配置在全局变量中。任何全局认证信息提供者实例都可以设置和访问全局认证信息。
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct GlobalCredentialProvider;
static GLOBAL_CREDENTIAL: Lazy<RwLock<Option<Credential>>> = Lazy::new(|| RwLock::new(None));
impl GlobalCredentialProvider {
/// 配置全局认证信息
#[inline]
pub fn setup(credential: Credential) {
let mut global_credential = GLOBAL_CREDENTIAL.write().unwrap();
*global_credential = Some(credential);
}
/// 清空全局认证信息
#[inline]
pub fn clear() {
let mut global_credential = GLOBAL_CREDENTIAL.write().unwrap();
*global_credential = None;
}
}
impl CredentialProvider for GlobalCredentialProvider {
#[inline]
fn get(&self, _opts: GetOptions) -> IoResult<GotCredential> {
if let Some(credential) = GLOBAL_CREDENTIAL.read().unwrap().as_ref() {
Ok(credential.to_owned().into())
} else {
Err(IoError::new(
IoErrorKind::Other,
"GlobalCredentialProvider is not setuped, please call GlobalCredentialProvider::setup() to do it",
))
}
}
}
impl Debug for GlobalCredentialProvider {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut d = f.debug_struct("GlobalCredentialProvider");
d.field("credential", &GLOBAL_CREDENTIAL.read().unwrap());
d.finish()
}
}
/// 环境变量认证信息提供者,可以将认证信息配置在环境变量中。
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct EnvCredentialProvider;
/// 设置七牛 AccessKey 的环境变量
pub const QINIU_ACCESS_KEY_ENV_KEY: &str = "QINIU_ACCESS_KEY";
/// 设置七牛 SecretKey 的环境变量
pub const QINIU_SECRET_KEY_ENV_KEY: &str = "QINIU_SECRET_KEY";
impl EnvCredentialProvider {
/// 配置环境变量认证信息提供者
#[inline]
pub fn setup(credential: &Credential) {
env::set_var(QINIU_ACCESS_KEY_ENV_KEY, credential.access_key().as_str());
env::set_var(QINIU_SECRET_KEY_ENV_KEY, credential.secret_key().as_str());
}
sourcepub fn sign(&self, data: &[u8]) -> String
pub fn sign(&self, data: &[u8]) -> String
使用七牛签名算法对数据进行签名
use qiniu_credential::{Credential, prelude::*};
let credential = Credential::new("abcdefghklmnopq", "1234567890");
assert_eq!(
credential.get(Default::default())?.sign(b"hello"),
"abcdefghklmnopq:b84KVc-LroDiz0ebUANfdzSRxa0="
);
Examples found in repository?
src/lib.rs (line 242)
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
pub fn sign_with_data(&self, data: &[u8]) -> String {
let encoded_data = base64::urlsafe(data);
self.sign(encoded_data.as_bytes()) + ":" + &encoded_data
}
/// 使用七牛签名算法 V1 对 HTTP 请求(请求体为内存数据)进行签名,返回 Authorization 的值
///
/// ```
/// use qiniu_credential::{Credential, HeaderValue, prelude::*};
/// use mime::APPLICATION_WWW_FORM_URLENCODED;
/// use std::io::Cursor;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let authorization = credential
/// .get(Default::default())?
/// .authorization_v1_for_request(
/// &"http://upload.qiniup.com/".parse()?,
/// Some(&HeaderValue::from_str(APPLICATION_WWW_FORM_URLENCODED.as_ref())?),
/// b"name=test&language=go"
/// );
/// # Ok(())
/// # }
/// ```
pub fn authorization_v1_for_request(&self, url: &Uri, content_type: Option<&HeaderValue>, body: &[u8]) -> String {
let authorization_token = sign_request_v1(self, url, content_type, body);
"QBox ".to_owned() + &authorization_token
}
/// 使用七牛签名算法 V1 对 HTTP 请求(请求体为输入流)进行签名,返回 Authorization 的值
///
/// 该方法的异步版本为 [`Credential::authorization_v1_for_request_with_async_body_reader`]。
///
/// ```
/// use qiniu_credential::{Credential, HeaderValue, prelude::*};
/// use std::io::Cursor;
/// use mime::APPLICATION_WWW_FORM_URLENCODED;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let authorization = credential
/// .get(Default::default())?
/// .authorization_v1_for_request_with_body_reader(
/// &"http://upload.qiniup.com/".parse()?,
/// Some(&HeaderValue::from_str(APPLICATION_WWW_FORM_URLENCODED.as_ref())?),
/// &mut Cursor::new(b"name=test&language=go")
/// )?;
/// # Ok(())
/// # }
/// ```
pub fn authorization_v1_for_request_with_body_reader(
&self,
url: &Uri,
content_type: Option<&HeaderValue>,
body: &mut dyn Read,
) -> IoResult<String> {
let authorization_token = sign_request_v1_with_body_reader(self, url, content_type, body)?;
Ok("QBox ".to_owned() + &authorization_token)
}
/// 使用七牛签名算法 V2 对 HTTP 请求(请求体为内存数据)进行签名,返回 Authorization 的值
///
/// ```
/// use qiniu_credential::{Credential, Method, HeaderMap, HeaderValue, prelude::*};
/// use http::header::CONTENT_TYPE;
/// use mime::APPLICATION_JSON;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let mut headers = HeaderMap::new();
/// headers.insert(CONTENT_TYPE, HeaderValue::from_str(APPLICATION_JSON.as_ref())?);
/// let authorization = credential
/// .get(Default::default())?
/// .authorization_v2_for_request(
/// &Method::GET,
/// &"http://upload.qiniup.com/".parse()?,
/// &headers,
/// b"{\"name\":\"test\"}".as_slice(),
/// );
/// # Ok(())
/// # }
/// ```
pub fn authorization_v2_for_request(&self, method: &Method, url: &Uri, headers: &HeaderMap, body: &[u8]) -> String {
let authorization_token = sign_request_v2(self, method, url, headers, body);
"Qiniu ".to_owned() + &authorization_token
}
/// 使用七牛签名算法 V2 对 HTTP 请求(请求体为输入流)进行签名,返回 Authorization 的值
///
/// 该方法的异步版本为 [`Credential::authorization_v2_for_request_with_async_body_reader`]。
///
/// ```
/// use qiniu_credential::{Credential, Method, HeaderMap, HeaderValue, prelude::*};
/// use http::header::CONTENT_TYPE;
/// use mime::APPLICATION_JSON;
/// use std::io::Cursor;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let mut headers = HeaderMap::new();
/// headers.insert(CONTENT_TYPE, HeaderValue::from_str(APPLICATION_JSON.as_ref())?);
/// let authorization = credential
/// .get(Default::default())?
/// .authorization_v2_for_request_with_body_reader(
/// &Method::GET,
/// &"http://upload.qiniup.com/".parse()?,
/// &headers,
/// &mut Cursor::new(b"{\"name\":\"test\"}")
/// )?;
/// # Ok(())
/// # }
/// ```
pub fn authorization_v2_for_request_with_body_reader(
&self,
method: &Method,
url: &Uri,
headers: &HeaderMap,
body: &mut dyn Read,
) -> IoResult<String> {
let authorization_token = sign_request_v2_with_body_reader(self, method, url, headers, body)?;
Ok("Qiniu ".to_owned() + &authorization_token)
}
/// 对对象的下载 URL 签名,可以生成私有存储空间的下载地址
///
/// ```
/// use qiniu_credential::{Credential, prelude::*};
/// use std::time::Duration;
/// # fn main() -> anyhow::Result<()> {
/// let credential = Credential::new("abcdefghklmnopq", "1234567890");
/// let url = "http://www.qiniu.com/?go=1".parse()?;
/// let url = credential
/// .get(Default::default())?
/// .sign_download_url(url, Duration::from_secs(3600));
/// println!("{}", url);
/// Ok(())
/// }
/// ```
pub fn sign_download_url(&self, url: Uri, lifetime: Duration) -> Uri {
let deadline = SystemTime::now() + lifetime;
let deadline = deadline
.duration_since(UNIX_EPOCH)
.expect("Invalid UNIX Timestamp")
.as_secs();
let to_sign = append_query_pairs_to_url(url, &[("e", &deadline.to_string())]);
let signature = self.sign(to_sign.to_string().as_bytes());
return append_query_pairs_to_url(to_sign, &[("token", &signature)]);
fn append_query_pairs_to_url(url: Uri, pairs: &[(&str, &str)]) -> Uri {
let path_string = url.path().to_owned();
let query_string = url.query().unwrap_or_default().to_owned();
let mut serializer = form_urlencoded::Serializer::new(query_string);
for (key, value) in pairs.iter() {
serializer.append_pair(key, value);
}
let query_string = serializer.finish();
let mut path_and_query = path_string;
if !query_string.is_empty() {
path_and_query.push('?');
path_and_query.push_str(&query_string);
}
let parts = url.into_parts();
let mut builder = Uri::builder();
if let Some(scheme) = parts.scheme {
builder = builder.scheme(scheme);
}
if let Some(authority) = parts.authority {
builder = builder.authority(authority);
}
builder.path_and_query(&path_and_query).build().unwrap()
}
}
sourcepub fn sign_reader(&self, reader: &mut dyn Read) -> IoResult<String>
pub fn sign_reader(&self, reader: &mut dyn Read) -> IoResult<String>
使用七牛签名算法对输入流数据进行签名
该方法的异步版本为 Credential::sign_async_reader
。
use qiniu_credential::{Credential, prelude::*};
use std::io::Cursor;
let credential = Credential::new("abcdefghklmnopq", "1234567890");
assert_eq!(
credential
.get(Default::default())?
.sign_reader(&mut Cursor::new(b"world"))?,
"abcdefghklmnopq:VjgXt0P_nCxHuaTfiFz-UjDJ1AQ="
);
sourcepub fn sign_with_data(&self, data: &[u8]) -> String
pub fn sign_with_data(&self, data: &[u8]) -> String
使用七牛签名算法对数据进行签名,并同时给出签名和原数据
use qiniu_credential::{Credential, prelude::*};
use std::io::Cursor;
let credential = Credential::new("abcdefghklmnopq", "1234567890");
assert_eq!(
credential.get(Default::default())?.sign_with_data(b"hello"),
"abcdefghklmnopq:BZYt5uVRy1RVt5ZTXbaIt2ROVMA=:aGVsbG8="
);
使用七牛签名算法 V1 对 HTTP 请求(请求体为内存数据)进行签名,返回 Authorization 的值
use qiniu_credential::{Credential, HeaderValue, prelude::*};
use mime::APPLICATION_WWW_FORM_URLENCODED;
use std::io::Cursor;
let credential = Credential::new("abcdefghklmnopq", "1234567890");
let authorization = credential
.get(Default::default())?
.authorization_v1_for_request(
&"http://upload.qiniup.com/".parse()?,
Some(&HeaderValue::from_str(APPLICATION_WWW_FORM_URLENCODED.as_ref())?),
b"name=test&language=go"
);
使用七牛签名算法 V1 对 HTTP 请求(请求体为输入流)进行签名,返回 Authorization 的值
该方法的异步版本为 Credential::authorization_v1_for_request_with_async_body_reader
。
use qiniu_credential::{Credential, HeaderValue, prelude::*};
use std::io::Cursor;
use mime::APPLICATION_WWW_FORM_URLENCODED;
let credential = Credential::new("abcdefghklmnopq", "1234567890");
let authorization = credential
.get(Default::default())?
.authorization_v1_for_request_with_body_reader(
&"http://upload.qiniup.com/".parse()?,
Some(&HeaderValue::from_str(APPLICATION_WWW_FORM_URLENCODED.as_ref())?),
&mut Cursor::new(b"name=test&language=go")
)?;
使用七牛签名算法 V2 对 HTTP 请求(请求体为内存数据)进行签名,返回 Authorization 的值
use qiniu_credential::{Credential, Method, HeaderMap, HeaderValue, prelude::*};
use http::header::CONTENT_TYPE;
use mime::APPLICATION_JSON;
let credential = Credential::new("abcdefghklmnopq", "1234567890");
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_str(APPLICATION_JSON.as_ref())?);
let authorization = credential
.get(Default::default())?
.authorization_v2_for_request(
&Method::GET,
&"http://upload.qiniup.com/".parse()?,
&headers,
b"{\"name\":\"test\"}".as_slice(),
);
使用七牛签名算法 V2 对 HTTP 请求(请求体为输入流)进行签名,返回 Authorization 的值
该方法的异步版本为 Credential::authorization_v2_for_request_with_async_body_reader
。
use qiniu_credential::{Credential, Method, HeaderMap, HeaderValue, prelude::*};
use http::header::CONTENT_TYPE;
use mime::APPLICATION_JSON;
use std::io::Cursor;
let credential = Credential::new("abcdefghklmnopq", "1234567890");
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_str(APPLICATION_JSON.as_ref())?);
let authorization = credential
.get(Default::default())?
.authorization_v2_for_request_with_body_reader(
&Method::GET,
&"http://upload.qiniup.com/".parse()?,
&headers,
&mut Cursor::new(b"{\"name\":\"test\"}")
)?;
sourcepub fn sign_download_url(&self, url: Uri, lifetime: Duration) -> Uri
pub fn sign_download_url(&self, url: Uri, lifetime: Duration) -> Uri
对对象的下载 URL 签名,可以生成私有存储空间的下载地址
use qiniu_credential::{Credential, prelude::*};
use std::time::Duration;
let credential = Credential::new("abcdefghklmnopq", "1234567890");
let url = "http://www.qiniu.com/?go=1".parse()?;
let url = credential
.get(Default::default())?
.sign_download_url(url, Duration::from_secs(3600));
println!("{}", url);
Ok(())
}
sourcepub async fn sign_async_reader(
&self,
reader: &mut (dyn AsyncRead + Send + Unpin)
) -> IoResult<String>
Available on crate feature async
only.
pub async fn sign_async_reader(
&self,
reader: &mut (dyn AsyncRead + Send + Unpin)
) -> IoResult<String>
async
only.使用七牛签名算法对异步输入流数据进行签名
use qiniu_credential::{Credential, prelude::*};
use futures_lite::io::Cursor;
let credential = Credential::new("abcdefghklmnopq", "1234567890");
assert_eq!(
credential
.async_get(Default::default()).await?
.sign_async_reader(&mut Cursor::new(b"world")).await?,
"abcdefghklmnopq:VjgXt0P_nCxHuaTfiFz-UjDJ1AQ="
);
Available on crate feature async
only.
async
only.使用七牛签名算法 V1 对 HTTP 请求(请求体为异步输入流)进行签名,返回 Authorization 的值
use qiniu_credential::{Credential, HeaderValue, prelude::*};
use mime::APPLICATION_WWW_FORM_URLENCODED;
use futures_lite::io::Cursor;
let credential = Credential::new("abcdefghklmnopq", "1234567890");
let authorization = credential
.async_get(Default::default()).await?
.authorization_v1_for_request_with_async_body_reader(
&"http://upload.qiniup.com/".parse()?,
Some(&HeaderValue::from_str(APPLICATION_WWW_FORM_URLENCODED.as_ref())?),
&mut Cursor::new(b"name=test&language=go")
).await?;
Available on crate feature async
only.
async
only.使用七牛签名算法 V2 对 HTTP 请求(请求体为异步输入流)进行签名,返回 Authorization 的值
use qiniu_credential::{Credential, Method, HeaderMap, HeaderValue, prelude::*};
use http::header::CONTENT_TYPE;
use mime::APPLICATION_JSON;
use futures_lite::io::Cursor;
#[async_std::main]
let credential = Credential::new("abcdefghklmnopq", "1234567890");
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_str(APPLICATION_JSON.as_ref())?);
let authorization = credential
.async_get(Default::default()).await?
.authorization_v2_for_request_with_async_body_reader(
&Method::GET,
&"http://upload.qiniup.com/".parse()?,
&headers,
&mut Cursor::new(b"{\"name\":\"test\"}")
).await?;
Trait Implementations§
source§impl Clone for GotCredential
impl Clone for GotCredential
source§fn clone(&self) -> GotCredential
fn clone(&self) -> GotCredential
Returns a copy of the value. Read more
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source
. Read moresource§impl CredentialProvider for GotCredential
impl CredentialProvider for GotCredential
source§fn get(&self, _opts: GetOptions) -> IoResult<GotCredential>
fn get(&self, _opts: GetOptions) -> IoResult<GotCredential>
返回七牛认证信息 Read more
source§fn async_get(
&self,
opts: GetOptions
) -> Pin<Box<dyn Future<Output = IoResult<GotCredential>> + Send + '_>>
fn async_get(
&self,
opts: GetOptions
) -> Pin<Box<dyn Future<Output = IoResult<GotCredential>> + Send + '_>>
Available on crate feature
async
only.异步返回七牛认证信息
source§impl Debug for GotCredential
impl Debug for GotCredential
source§impl Deref for GotCredential
impl Deref for GotCredential
source§impl DerefMut for GotCredential
impl DerefMut for GotCredential
source§impl From<Credential> for GotCredential
impl From<Credential> for GotCredential
source§fn from(credential: Credential) -> Self
fn from(credential: Credential) -> Self
Converts to this type from the input type.
source§impl From<GotCredential> for Credential
impl From<GotCredential> for Credential
source§fn from(result: GotCredential) -> Self
fn from(result: GotCredential) -> Self
Converts to this type from the input type.
source§impl PartialEq<GotCredential> for GotCredential
impl PartialEq<GotCredential> for GotCredential
source§fn eq(&self, other: &GotCredential) -> bool
fn eq(&self, other: &GotCredential) -> bool
This method tests for
self
and other
values to be equal, and is used
by ==
.