Example #1
0
        public void Constructor_ValidHttpsUri_SentryUriHasHttpsScheme()
        {
            var dsn = new Dsn(TestHelper.DsnUri);

            Assert.That(dsn.SentryUri, Is.Not.Null);
            Assert.That(dsn.SentryUri.Scheme, Is.EqualTo("https"));
        }
        public static void RavenStorageTestsInit(TestContext context)
        {
            Dsn dsn = new Dsn(RavenConfig.DSN);
            RavenClient.InitializeAsync(dsn);

            _storageClient = new RavenStorageClient();
        }
Example #3
0
        public void Constructor_ValidHttpsUri_UriIsEqualToDsn()
        {
            var dsn = new Dsn(TestHelper.DsnUri);

            Assert.That(dsn.Uri, Is.Not.Null);
            Assert.That(dsn.Uri.ToString(), Is.EqualTo(TestHelper.DsnUri));
        }
Example #4
0
        public void Constructor_ValidHttpUri_SentryUriHasHttpScheme()
        {
            const string dsnUri =
                "http://*****:*****@app.getsentry.com/3739";
            var dsn = new Dsn(dsnUri);

            Assert.That(dsn.SentryUri, Is.Not.Null);
            Assert.That(dsn.SentryUri.Scheme, Is.EqualTo("http"));
        }
        public void CreateAuthenticationHeader_ReturnsCorrectAuthenticationHeader()
        {
            const string expected =
                @"^Sentry sentry_version=4, sentry_client=SharpRaven/[\d\.]+, sentry_timestamp=\d+, sentry_key=7d6466e66155431495bdb4036ba9a04b, sentry_secret=4c1cfeab7ebd4c1cb9e18008173a3630$";

            var dsn = new Dsn(
                "https://*****:*****@app.getsentry.com/3739");

            var authenticationHeader = PacketBuilder.CreateAuthenticationHeader(dsn);

            Assert.That(authenticationHeader, Is.StringMatching(expected));
        }
Example #6
0
 /// <summary>
 /// Creates the authentication header base on the provided <see cref="Dsn"/>.
 /// </summary>
 /// <param name="dsn">The DSN.</param>
 /// <returns>
 /// The authentication header.
 /// </returns>
 public static string CreateAuthenticationHeader(Dsn dsn)
 {
     return String.Format("Sentry sentry_version={0}"
                          + ", sentry_client={1}"
                          + ", sentry_timestamp={2}"
                          + ", sentry_key={3}"
                          + ", sentry_secret={4}",
                          SentryVersion,
                          UserAgent,
                          (long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds,
                          dsn.PublicKey,
                          dsn.PrivateKey);
 }
Example #7
0
        public void Test_Create_Valid_Dsn()
        {
            try
            {
                Dsn dsn = new Dsn("http://*****:*****@example.com/projectid");

                Assert.AreEqual("public", dsn.PublicKey);
                Assert.AreEqual("private", dsn.PrivateKey);
                Assert.AreEqual("projectid", dsn.ProjectID);
            }
            catch (ArgumentException ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        public OptionalHub(SentryOptions options)
        {
            options.SetupLogging();

            if (options.Dsn == null)
            {
                if (!Dsn.TryParse(DsnLocator.FindDsnStringOrDisable(), out var dsn))
                {
                    options.DiagnosticLogger?.LogWarning("Init was called but no DSN was provided nor located. Sentry SDK will be disabled.");
                    _hub = DisabledHub.Instance;
                    return;
                }
                options.Dsn = dsn;
            }

            _hub = new Hub(options);
        }
Example #9
0
        public async Task CapturesRequestData(string eventId,
                                              string method,
                                              string url)
        {
            var uri = new Uri(url, UriKind.Absolute);

            var reqMock = new Mock <HttpRequest>();

            reqMock.SetupGet(r => r.Method).Returns(method);
            reqMock.SetupGet(r => r.Scheme).Returns(uri.Scheme);
            reqMock.SetupGet(r => r.Host).Returns(new HostString(uri.Host));
            reqMock.SetupGet(r => r.Path).Returns(uri.AbsolutePath);

            reqMock.SetupGet(r => r.QueryString)
            .Returns(QueryString.FromUriComponent(uri.Query));
            reqMock.SetupGet(r => r.Query)
            .Returns(new QueryCollection(QueryHelpers.ParseQuery(uri.Query)));

            var httpMock = new Mock <HttpContext>();

            httpMock.Setup(m => m.Items)
            .Returns(new Dictionary <object, object>());

            httpMock.SetupGet(c => c.Request)
            .Returns(reqMock.Object);

            var clientMock = new Mock <SentryClient>(
                Dsn.Create(ExceptionReportingOptions.Dsn));

            clientMock.Setup(c => c.SendEventAsync(It.Is <SentryEventData>(r
                                                                           => r.Request.Url == url.Split('?', StringSplitOptions.None)[0] &&
                                                                           r.Request.Method == method &&
                                                                           r.Request.QueryString == uri.Query)))
            .ReturnsAsync(new SentryResponse {
                EventId = eventId
            })
            .Verifiable();

            var middleware = CreateMiddleware(Next_Throw, clientMock.Object);

            await Assert.ThrowsAsync <InvalidOperationException>(
                () => middleware.Invoke(httpMock.Object));

            clientMock.Verify();
        }
        public string Send(JsonPacket packet, Dsn dsn)
        {
            try
            {
                var ts         = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
                var webRequest = (HttpWebRequest)WebRequest.Create(dsn.SentryUri);
                webRequest.Method = "POST";
                webRequest.Accept = "application/json";
                webRequest.Headers["X-Sentry-Auth"] = $"Sentry sentry_version={7},sentry_client=steepshot/1, sentry_timestamp={ts}, sentry_key={dsn.PublicKey}, sentry_secret={dsn.PrivateKey}";
                webRequest.ContentType = "application/json; charset=utf-8";

                using (var s = webRequest.GetRequestStreamAsync().Result)
                {
                    var txt = packet.ToString();
                    using (var sw = new StreamWriter(s))
                    {
                        sw.Write(txt);
                    }
                }

                using (var wr = webRequest.GetResponseAsync().Result)
                {
                    using (var responseStream = wr.GetResponseStream())
                    {
                        if (responseStream == null)
                        {
                            return(null);
                        }

                        using (var sr = new StreamReader(responseStream))
                        {
                            var content  = sr.ReadToEnd();
                            var response = JsonConvert.DeserializeObject <JObject>(content);
                            return(response.Value <string>("id"));
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                return(exception.Message);
            }
        }
        public void CreateRequest_SentryUrl_FromOptions()
        {
            // Arrange
            var httpTransport = new HttpTransport(
                new SentryOptions {
                Dsn = DsnSamples.ValidDsnWithSecret
            },
                new HttpClient());

            var envelope = Envelope.FromEvent(new SentryEvent());

            var uri = Dsn.Parse(DsnSamples.ValidDsnWithSecret).GetEnvelopeEndpointUri();

            // Act
            var request = httpTransport.CreateRequest(envelope);

            // Assert
            request.RequestUri.Should().Be(uri);
        }
Example #12
0
        internal HttpRequestMessage CreateRequest(Envelope envelope)
        {
            if (string.IsNullOrWhiteSpace(_options.Dsn))
            {
                throw new InvalidOperationException("The DSN is expected to be set at this point.");
            }

            var dsn = Dsn.Parse(_options.Dsn);

            var request = new HttpRequestMessage
            {
                RequestUri = dsn.GetEnvelopeEndpointUri(),
                Method     = HttpMethod.Post,
                Content    = new SerializableHttpContent(envelope)
            };

            _addAuth(request.Headers);
            return(request);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpRequester"/> class.
        /// </summary>
        /// <param name="data">The request data.</param>
        /// <param name="dsn">The DSN used in this request</param>
        /// <param name="timeout">The request timeout.</param>
        /// <param name="useCompression">Whether to use compression or not.</param>
        public HttpRequester(RequestData data, Dsn dsn, TimeSpan timeout, bool useCompression)
        {
            this.data           = data ?? throw new ArgumentNullException(nameof(data));
            this.timeout        = timeout == default ? TimeSpan.FromSeconds(5) : timeout;
            this.useCompression = useCompression;

            this.webRequest = CreateWebRequest(dsn.SentryUri, dsn);

            if (useCompression)
            {
                this.webRequest.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");
                this.webRequest.AutomaticDecompression = DecompressionMethods.Deflate;
                this.webRequest.ContentType            = "application/octet-stream";
            }

            else
            {
                this.webRequest.ContentType = "application/json; charset=utf-8";
            }
        }
Example #14
0
        public SentryErrorReporting(string sentryURL, string environment, string version, string userGUID, Platform platform, string platformVersion, bool scrubUserName = false,
                                    Dictionary <string, string> extraTags = null)
        {
            _sentryDsn = new Dsn(sentryURL);
            _userGUID  = userGUID;
            InitialiseSentryClient();

            _sentryClient.Environment = environment;
            _sentryClient.Release     = version;
            _sentryClient.Tags["OS"]  = $"{platform} {platformVersion}";
            if (extraTags != null)
            {
                AddTags(extraTags);
            }

            if (scrubUserName)
            {
                _sentryClient.LogScrubber = new SentryUserScrubber();
            }
        }
Example #15
0
        public void SentryDsn_ContainsExpectedValues(string dsnValue)
        {
            var dsn    = Dsn.Create(dsnValue);
            var auth   = SentryAuth.Issue(dsn, IssuedAt);
            var values = SentryAuthHeader.GetValues(auth);

            Assert.Contains($"Sentry sentry_version={auth.SentryVersion}", values);
            Assert.Contains($"sentry_timestamp={auth.Timestamp}", values);
            Assert.Contains($"sentry_key={auth.PublicKey}", values);

            if (dsn.GetSecretKey() != null)
            {
                Assert.Contains($"sentry_secret={auth.SecretKey}", values);
            }
            else
            {
                Assert.DoesNotContain("sentry_secret", values);
            }

            Assert.Contains($"sentry_client={auth.ClientVersion}", values);
        }
Example #16
0
        private void DbConnectForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.DialogResult == DialogResult.OK)
            {
                bool rinf;

                rinf = this.DbOpen();// OKならINIファイルを更新して抜ける

                if (rinf != true)
                {
                    //NGだからダイアログを閉じない
                    e.Cancel = true;
                }
                else
                {
                    //OKだからINIファイル更新
                    aIniFile.WriteString("DataBase", "DSN", Dsn.Trim());
                    aIniFile.WriteString("DataBase", "UID", Uid.Trim());
                    aIniFile.WriteString("DataBase", "PWD", Pwd.Trim());
                }
            }
        }
Example #17
0
        internal Hub(ISentryClient client, SentryOptions options)
        {
            _ownedClient = client;

            _options = options;

            if (options.Dsn is null)
            {
                var dsn = DsnLocator.FindDsnStringOrDisable();

                if (Dsn.TryParse(dsn) is null)
                {
                    const string msg = "Attempt to instantiate a Hub without a DSN.";
                    options.DiagnosticLogger?.LogFatal(msg);
                    throw new InvalidOperationException(msg);
                }

                options.Dsn = dsn;
            }

            options.DiagnosticLogger?.LogDebug("Initializing Hub for Dsn: '{0}'.", options.Dsn);

            ScopeManager = new SentryScopeManager(options, _ownedClient);

            _integrations = options.Integrations;

            if (_integrations?.Length > 0)
            {
                foreach (var integration in _integrations)
                {
                    options.DiagnosticLogger?.LogDebug("Registering integration: '{0}'.", integration.GetType().Name);
                    integration.Register(this, options);
                }
            }

            // Push the first scope so the async local starts from here
            _rootScope = PushScope();
        }
        internal HttpRequestMessage CreateRequest(Envelope envelope)
        {
            if (string.IsNullOrWhiteSpace(_options.Dsn))
            {
                throw new InvalidOperationException("The DSN is expected to be set at this point.");
            }

            var dsn = Dsn.Parse(_options.Dsn);

            var authHeader =
                $"Sentry sentry_version={_options.SentryVersion}," +
                $"sentry_client={_options.ClientVersion}," +
                $"sentry_key={dsn.PublicKey}," +
                (dsn.SecretKey is { } secretKey ? $"sentry_secret={secretKey}," : null) +
                $"sentry_timestamp={_clock.GetUtcNow().ToUnixTimeSeconds()}";

            return(new HttpRequestMessage
            {
                RequestUri = dsn.GetEnvelopeEndpointUri(),
                Method = HttpMethod.Post,
                Headers = { { "X-Sentry-Auth", authHeader } },
                Content = new EnvelopeHttpContent(envelope)
            });
        }
Example #19
0
    public void Start()
    {
#if UNITY_EDITOR
        UnityEngine.Debug.LogWarning("This script is running in editormode. It will not send any message to sentry.");
        return;
#endif

        if (Dsn == string.Empty)
        {
            // Empty string = disabled SDK
            UnityDebug.LogWarning("No DSN defined. The Sentry SDK will be disabled.");
            return;
        }

        if (_instance == null)
        {
            try
            {
                _dsn = new Dsn(Dsn);
            }
            catch (Exception e)
            {
                UnityDebug.LogError(string.Format("Error parsing DSN: {0}", e.Message));
                return;
            }

            _breadcrumbs = new Breadcrumb[Breadcrumb.MaxBreadcrumbs];
            DontDestroyOnLoad(this);
            _instance    = this;
            _initialized = true;
        }
        else
        {
            Destroy(this);
        }
    }
Example #20
0
        public async Task SendException_ReturnsEventId()
        {
            var client = Sentry.CreateClient(Dsn.Create(GetProductionDsn()));

            var value = 0;

            try
            {
                var x = 10 / value;
            }
            catch (Exception ex)
            {
                var response = await client.CaptureAsync(e => e
                                                         .SetException(ex)
                                                         .SetErrorLevel(ErrorLevel.Warning)
                                                         .AddExtraData("test", new
                {
                    IsTest = true
                })
                                                         .AddTag("test_tag", "yes"));

                Assert.NotNull(response.EventId);
            }
        }
Example #21
0
 public void IsDisabled_InvalidDsn_False() => Assert.False(Dsn.IsDisabled(DsnSamples.InvalidDsn));
Example #22
0
 public void IsDisabled_ValidDsn_False() => Assert.False(Dsn.IsDisabled(DsnSamples.ValidDsnWithSecret));
Example #23
0
 public void TryParse_NullDsn_ThrowsArgumentNull()
 {
     Assert.False(Dsn.TryParse(null, out var dsn));
     Assert.Null(dsn);
 }
Example #24
0
 public void TryParse_NullDsn_ThrowsArgumentNull()
 {
     Assert.Null(Dsn.TryParse(null));
 }
Example #25
0
 private static Dsn GetDsn(SentryOptions options)
 => !string.IsNullOrEmpty(options.Dsn)
         ? Dsn.Create(options.Dsn)
         : null;
Example #26
0
 public void IsDisabled_EmptyStringDsn_True() => Assert.True(Dsn.IsDisabled(string.Empty));
Example #27
0
 public void TryParse_SampleInvalidDsn_Fails()
 {
     Assert.False(Dsn.TryParse(DsnSamples.InvalidDsn, out var dsn));
     Assert.Null(dsn);
 }
Example #28
0
 public void TryParse_SampleValidDsnWithSecret_Succeeds()
 {
     Assert.True(Dsn.TryParse(DsnSamples.ValidDsnWithSecret, out var dsn));
     Assert.NotNull(dsn);
 }
Example #29
0
        public void Ctor_DisableSdk_ThrowsUriFormatException()
        {
            var ex = Assert.Throws <UriFormatException>(() => Dsn.Parse(Constants.DisableSdkDsnValue));

            Assert.Equal("Invalid URI: The URI is empty.", ex.Message);
        }
Example #30
0
 protected override string Send(JsonPacket packet, Dsn dsn)
 {
     return packet.Project;
 }
Example #31
0
 public void ToString_ReturnsStringEqualToDsn()
 {
     var dsn = new Dsn(TestHelper.DsnUri);
     Assert.That(dsn.ToString(), Is.EqualTo(TestHelper.DsnUri));
 }
Example #32
0
 public void IsDisabled_NullDsn_False() => Assert.False(Dsn.IsDisabled(null));
Example #33
0
 public TestableRavenClient(Dsn dsn, IJsonPacketFactory jsonPacketFactory)
     : base(dsn, jsonPacketFactory)
 {
     // This constructor must exist so Nancy can inject the Dsn and NancyContextJsonPacketFactory
     // that is registered in SentryRegistrations. @asbjornu
     this.dsn = dsn;
 }
Example #34
0
 public void IsDisabled_DisabledDsn_True() => Assert.True(Dsn.IsDisabled(Constants.DisableSdkDsnValue));
Example #35
0
 public void TryParse_DisabledSdk_Fails()
 {
     Assert.False(Dsn.TryParse(Constants.DisableSdkDsnValue, out var dsn));
     Assert.Null(dsn);
 }
Example #36
0
        public void Ctor_NotUri_ThrowsUriFormatException()
        {
            var ex = Assert.Throws <UriFormatException>(() => Dsn.Parse("Not a URI"));

            Assert.Equal("Invalid URI: The format of the URI could not be determined.", ex.Message);
        }
Example #37
0
        public void Ctor_SampleValidDsnWithSecret_CorrectlyConstructs()
        {
            var dsn = new Dsn(DsnSamples.ValidDsnWithSecret);

            Assert.Equal(DsnSamples.ValidDsnWithSecret, dsn.ToString());
        }
 public static void RavenClientTestsInit(TestContext context)
 {
     Dsn dsn = new Dsn(RavenConfig.DSN);
     RavenClient.InitializeAsync(dsn);
 }
Example #39
0
 public void TryParse_EmptyStringDsn_ThrowsUriFormatException()
 {
     Assert.False(Dsn.TryParse(string.Empty, out var dsn));
     Assert.Null(dsn);
 }
Example #40
0
 public void TryParse_NotUri_Fails()
 {
     Assert.False(Dsn.TryParse("Not a URI", out var dsn));
     Assert.Null(dsn);
 }
Example #41
0
 public TestableSentryClient(Dsn dsn,
                             Func <SentryEventData, SentryResponse> onSend) : base(dsn)
     => _onSend = onSend;